Search code examples
c#winformscontrol-array

Correct way to add controls dynamically


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;
}

I debugged my app and checkBoxArray (after the loop) is all the same.

The second issue is how do I add my controls to the WinForm?


Solution

  • It looks like you're actually working with some class-level member called checkBox instead of the locally-scoped one:

    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
    }
    

    I'm not sure what the purpose of the checkBoxArray is, but if it was just an attempt to get things working, you can safely get rid of it.