简体   繁体   English

C#中的DataGridViews数组

[英]Array of DataGridViews in C#

I am working on a program that contains multiple DataGridViews on multiple tab controls. 我正在开发一个程序,该程序在多个选项卡控件上包含多个DataGridViews。 My DataGridViews have a lot of initial formatting done to them at runtime. 我的DataGridView在运行时对它们做了很多初始格式化。 For example, row 0 and 1 are my first set of "headers" which are read only cells with color and font formatting. 例如,行0和1是我的第一组“标题”,它们是具有颜色和字体格式的只读单元格。 Rows 2 and 3 are for data entry with color coding based on values entered. 第2行和第3行用于根据输入的值进行颜色编码的数据输入。 Then, this row organization repeats for rows 4, 5, 6, and 7, then, so on. 然后,此行组织重复第4、5、6和7行,依此类推。

I do not want to have to repeat all the setup and formatting code for all the other DataGridViews. 我不想为所有其他DataGridViews重复所有设置和格式化代码。 Is there a way to create an array of DataGridViews so that I can loop the setup and formatting code? 有没有一种方法可以创建一个DataGridViews数组,以便我可以循环设置和格式化代码?

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]. 我无法在窗体subFrame [0]上命名DataGridView控件。 Do I have to create the control and define placement, etc in code to do this? 我是否必须在代码中创建控件并定义放置等? Or is there another way? 还是有另一种方法?

If you're generating the DataGridView s dynamically then you can use exactly the approach you propose. 如果要动态生成DataGridView则可以完全使用您建议的方法。 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. 表单上控件的实例是C#中的对象,就像其他对象一样,因此您可以在数组中保留对这些对象的引用。

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. 您要针对此特定问题合并的代码将在ApplyStyling() ,实质上是按照您所描述的那样变换每个网格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM