radensb
radensb

Reputation: 694

Array of DataGridViews in C#

I am working on a program that contains multiple DataGridViews on multiple tab controls. My DataGridViews have a lot of initial formatting done to them at runtime. For example, row 0 and 1 are my first set of "headers" which are read only cells with color and font formatting. Rows 2 and 3 are for data entry with color coding based on values entered. Then, this row organization repeats for rows 4, 5, 6, and 7, then, so on.

I do not want to have to repeat all the setup and formatting code for all the other DataGridViews. Is there a way to create an array of DataGridViews so that I can loop the setup and formatting code?

DataGridView[] subFrames = new DataGridView[16];

The above compiles, but how does one use this? I cannot name a DataGridView control on my form subFrame[0]. Do I have to create the control and define placement, etc in code to do this? Or is there another way?

Upvotes: 0

Views: 237

Answers (1)

David
David

Reputation: 218798

If you're generating the DataGridViews dynamically then you can use exactly the approach you propose. Instances of controls on a form are objects in C# like any other, so you can hold a reference to those objects in an array.

Not knowing much of your code, this is a bit of a contrived example. But consider this pattern:

public class Form1
{
    private DataGridView[] subFrames = new DataGridView[16];

    // other code

    private void BuildGrids()
    {
        this.DataGridView1 = BuildFirstGrid();
        subFrames[0] = this.DataGridView1;
        // continue for the rest of the grids
    }

    private void StyleGrids()
    {
        foreach (var grid in subFrames)
            ApplyStyling(grid);
    }
}

The code you're looking to consolidate for this specific question would be in ApplyStyling(), essentially transforming each grid as you describe.

Upvotes: 1

Related Questions