I
I
idShura2017-11-02 19:32:59
Python
idShura, 2017-11-02 19:32:59

How to make a method for different forms?

Tell me if I'm doing it right?
The application has several forms. Each form has a DataGridView. With each DataGridView, I need to perform the same set of actions. In order not to duplicate the code in the forms, I created the Main class and in each form I create an instance of this class.

class Main
    {
        public void defaultSettingDataGridView(Control c)
        {
            if (c.GetType() == typeof(DataGridView))
            {
                DataGridView dgv = c as DataGridView;

                SetDoubleBuffered(dgv, true);

                dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgv.AllowUserToAddRows = false;

                // ...
            }
        }

        private void example(Control c, bool value)
        {
            // ...
        }
    }

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            Main m = new Main();
            m.defaultSettingDataGridView(dataGridView1);
        }

    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yura Khlyan, 2019-08-08
@mafioznic161

IndexError: list index out of range - you want to take an element from the list, but there are not so many elements in the list

C
cicatrix, 2017-11-02
@idShura

It’s easier to make a separate class (it can be static), make a method in it that would take a link to your DataGridView as an input, and would do what you need with it.

internal static class Helper
{
      internal static void SetUpGridView(DataGridView dgv)
     {
       // ... делайте всё здесь
     }
} // class Helper

Well, in the form class it's simple:
Helper.SetUpGridView(this.DataGridView1);

L
lvv85, 2017-11-02
@lvv85

You can write an extension method for the DataGridView.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question