创建动态控件
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]);
它在 verGroup[i].Name 处给了我一个 IndexOutofRangeException。但是index是0,这肯定是它想要的吧?
我也尝试过
verGroup = new GroupBox[5]
,但这会引发“对象引用未设置为对象的实例”错误。
如果有人能指出我正确的方向,我将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于 amount 从 0 开始,并且您创建了一个大小为 i 的数组,因此您正在创建一个大小为 0 的数组。因此您无法索引数组中的任何内容,因为它的长度为 0。
第二个错误是因为您不这样做t 初始化组框。你需要说 verGroup[i] = new GroupBox();来初始化它。
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.
首先,您在此处分配一个
GroupBox
数组:但是,这不会分配数组内的 GroupBox 值。这需要单独处理:
此外,如果
i
为 0,则表示创建零个组框,然后尝试访问第一个 (verGroup[0]
是第一个元素),这将会失败。你可能需要这样做:First off, you're allocating an array of
GroupBox
here:However, this doesn't allocate the GroupBox values within the array. This will need to be handled separately:
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:你的代码很糟糕,你只需要创建一次数组。然后您需要实例化数组中的每个项目。
Your code is pretty broken, you need to create the array only once. then you need to instantiate each item in the array.
你必须有一个充分的理由来解释为什么你要创建一个数组
you must have a good reason for why you are creating an array