Creating dynamic controls

守給你的承諾、 提交于 2019-12-11 12:19:34

问题


        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.


回答1:


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.




回答2:


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



回答3:


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
}



回答4:


    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



来源:https://stackoverflow.com/questions/4995168/creating-dynamic-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!