David M
David M

Reputation: 2943

Creating dynamic controls

        int i = amount; //amount will always start at 0
        int j = i + 1;

        GroupBox[] verGroup;
        verGroup = new GroupBox[i];

        verGroup[i].Name = "verGroup" + i.ToString();
        verGroup[i].Width = 400;
        verGroup[i].Height = 120;
        verGroup[i].Left = 5;
        verGroup[i].Top = 5 + (verGroup[i].Height * i) + (10 * i);
        verGroup[i].Text = "Verification #" + j.ToString();

        pnlVer.Controls.Add(verGroup[i]);

It gives me an IndexOutofRangeException at verGroup[i].Name. But index is 0, which is surely what it wants?

I've also tried

 verGroup = new GroupBox[5]  

but that throws an "Object reference not set to an instance of an object" error.

Would be appreciated if someone could point me in the right direction.

Upvotes: 1

Views: 1702

Answers (4)

Kris Ivanov
Kris Ivanov

Reputation: 10598

    int i = amount; //amount will always start at 0
    int j = i + 1;

    GroupBox[] verGroup;
    verGroup = new GroupBox[i];
    verGroup[i] = new GroupBox();

    verGroup[i].Name = "verGroup" + i.ToString();
    verGroup[i].Width = 400;
    verGroup[i].Height = 120;
    verGroup[i].Left = 5;
    verGroup[i].Top = 5 + (verGroup[i].Height * i) + (10 * i);
    verGroup[i].Text = "Verification #" + j.ToString();

    pnlVer.Controls.Add(verGroup[i]);

you must have a good reason for why you are creating an array

Upvotes: 0

Vadim
Vadim

Reputation: 17965

Your code is pretty broken, you need to create the array only once. then you need to instantiate each item in the array.

verGroup[] = new GroupBox[amount];
for (int i = 0; i < amount; i++)
{
    verGroup[i] = new GroupBox();
    //set values and add to controls
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564871

First off, you're allocating an array of GroupBox here:

GroupBox[] verGroup;
verGroup = new GroupBox[i];

However, this doesn't allocate the GroupBox values within the array. This will need to be handled separately:

GroupBox[] verGroup;
verGroup = new GroupBox[i];
for(int gb = 0; gb < i; ++gb)
   verGroup[gb] = new GroupBox(); // This creates the individual group box elements

Also, if i is 0, you're saying to create zero group boxes, then trying to access the first (verGroup[0] is the 1st element), which will fail. You need to probably do:

GroupBox[] verGroup;
verGroup = new GroupBox[i+1];
for(int gb = 0; gb < verGroup.Length; ++gb)
   verGroup[gb] = new GroupBox(); // This creates the individual group box elements

Upvotes: 0

Darkhydro
Darkhydro

Reputation: 2082

Since amount starts at 0, and you create an array of size i, you are creating an array of size 0. Therefore you can't index anything in the array, because it is of length 0.

the second error is because you don't initialize the group box. You need to say verGroup[i] = new GroupBox(); to initialize it.

Upvotes: 5

Related Questions