开发者

Adding checkbox dynamically

public Form1 f1 = new Form1();
int p = 150;
int q = 100;

public void add()
{
    //CheckBox c = new CheckBox();
    //c.Location = new Point(p, q);

    //c.Text = f1.sub[0];
    //this.Co开发者_如何转开发ntrols.Add(c);

    CheckBox chkBox = new CheckBox();
    chkBox.Location = new Point(p, q);
    chkBox.Text = "Checked";
    chkBox.Checked = false;
    chkBox.CheckState = CheckState.Checked;
    chkBox.CheckedChanged += new EventHandler(chkBox_CheckedChanged);//
    this.Controls.Add(chkBox);
    chkBox.Text = f1.sub[1];//The problem is here... whatever value I supply
                            // to sub[] it gives the below mentioned error
}

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Here sub[] is a list<string> in form1 which has 5 values...


Well it seems that at the time you access the sub collection, it is empty. Before executing this line: chkBox.Text = f1.sub[1]; see what you have in the collection.


Maybe the "official" Form1 (the one that you see on the screen) has a "sub" with 5 values, but does the newly created Form1 (from the f1 variable) also have 5 values? The errormessage says no ...

EDIT
IF you call that add() method from your Form1 instance, then pass this as parameter to the method instead of creating a new Form1().


Obviously, there is nothing at index position 1 in sub.

chkBox.Text = f1.sub[1];

The length of data in list sub is less than 2.

If you say that it contains 5 elements, then make sure that the reference to that object is still valid. I feel that your are not getting the data from a list which you wanted to, but rather an empty one, probably. In short, sub does not point to the list that you think it is.

Tip: Avoid hard-coding the values in the code as much as possible. Find the index programmatically and use it. Example (just demonstrating):

chkBox.Text = f1.sub[f1.sub.Count - 1];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜