WinForm 元素数组

Array of WinForm Elements

所以我的程序中确实有一个 WinForm,其中包含一系列的组合框和两个文本框。有 atm 8 行,但这将增加到至少 32 行,因此我想使用数组或类似的。我该怎么做?

我目前的工作方法是创建一个 TextBoxes/ComboBoxes 的新数组,我手动将其分配给 WinForm 的指定元素。因此我有一个这样的列表:

tbGU[0] = tbGU1;
tbGO[0] = tbGO1;
cbS[0] = cbS1;

当然,这看起来很糟糕,如果被复制很多次也不是很好。有人解决了我的问题吗?

我需要访问 ComboBox 的 SelectedIndex 和 TextBoxes 的 Text。 我希望我可以避免必须通过代码手动创建所有元素。

一个简单的解决方案是使用数组初始化语法:

ComboBox[] cbS = new[] { cbS1, cbS2, cbS3 ... };

另一种方法是完全删除变量 cbS1cbS2 ... cBSn 并在 for 循环中创建控件。

ComboxBox[] cbS = new ComboBox[32];
// declare the text box arrays here as well
for (int i = 0 ; i < cbS.Length ; i++) {
    cbS[i] = new ComboBox();
    cbS[i].Location = ... // use "i" to help you position the control
    // configure your combo box ...
    this.Controls.Add(cbS[i]);

    // do the same for the text boxes.
}

第三种方法是创建自定义控件:

// name this properly!
public class MyControl: UserControl {
    public ComboBox CbS { get; }
    public TextBox TbGU { get; }
    public TextBox TbGO { get; }

    public MyControl() {
        // create and configure the combo box and text boxes here ...
    }
}

然后您可以使用 for 循环创建很多 MyControls。