正确的动态添加控件的方法

时间:2014-04-04 16:37:53

标签: c# winforms control-array

CheckBox[] checkBoxArray = new CheckBox[lines.Count()];
CheckBox checkBox = new CheckBox();

int yLocation = 25;
int diff = 0;
int i = 0;
foreach(var line in lines)
{
    this.checkBox.Text = line;
    this.checkBox.Location = new System.Drawing.Point(90, yLocation + diff);
    this.checkBox.Size = new System.Drawing.Size(110, 30);
    checkBoxArray[i] = checkBox;
    i++;
    diff = diff + 30;
}

我调试了我的应用,checkBoxArray(循环之后)完全相同。

第二个问题是如何将我的控件添加到WinForm?

3 个答案:

答案 0 :(得分:3)

看起来您实际上正在使用一个名为checkBox的类级别成员而不是本地作用的成员:

CheckBox[] checkBoxArray = new CheckBox[lines.Count()];

int yLocation = 25;
int diff = 0;
int i = 0;
foreach(var line in lines)
{
    CheckBox checkBox = new CheckBox();
    checkBox.Text = line;
    checkBox.Location = new System.Drawing.Point(90, yLocation + diff);
    checkBox.Size = new System.Drawing.Size(110, 30);
    checkBoxArray[i] = checkBox;
    i++;
    diff = diff + 30;
    Controls.Add(checkBox);  // Add checkbox to form
}

我不确定checkBoxArray的目的是什么,但如果只是为了让事情有效,你可以安全地摆脱它。

答案 1 :(得分:2)

如果您未在循环中创建新的CheckBox实例,那么您只需一次又一次覆盖同一CheckBox上的值。

foreach (var line in lines)
{
    // Create a new CheckBox
    var checkBox = new CheckBox();

    // Set its properties
    checkBox.Text = line;
    ...

    // Add it to the form's collection of controls
    this.Controls.Add(checkBox);

    // Adjust checkBox.Location depending on where you want it
    checkBox.Location = new Point(0, 0);
}

答案 2 :(得分:1)

也许这会对你有所帮助:http://support.microsoft.com/kb/319266

this.Controls.Add(checkBox);