Question

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?

Was it helpful?

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.

OTHER TIPS

If you don't create a new CheckBox instance inside the loop, then you're just overwriting the values on the same CheckBox again and again.

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

Maybe this helps you a bit: http://support.microsoft.com/kb/319266

this.Controls.Add(checkBox);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top