0
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.Controls.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...

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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().

2 Comments

then wat should I do for that?
You need SOME way to get a reference to the visible Form1. Either from within that form (as in my example) or from the code that launched that Form1.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.