按钮单击事件中的异常 [英] exception in a button click event

查看:66
本文介绍了按钮单击事件中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码运行异常对象引用设置为对象的实例"此代码有什么问题?有人可以帮忙吗?

this code runs an exception "object reference is set to an instance of an object" what''s wrong in this code?can any one help me?

x = 40;
for (int i = 1; i <=can_Count; i++)
{
  bu1[index1] = new Button();
  bu1[index1].Name = "BI" + i;
  bu1[index1].Text = "1";
  bu1[index1].Location = new Point(20, x);
  bu1[index1].ForeColor = Color.Goldenrod;
  bu1[index1].BackColor = Color.Black;
  bu1[index1].Size = new Size(72, 47);
  x = x + 75;
  index1++;
  try
  {
   bu1[i].Click += new EventHandler(button1_Click);
  }
  catch (Exception ee)
  { MessageBox.Show(ee.Message); }
}
this.Controls.AddRange(bu1);



[edit]已添加代码块,忽略HTML ..."选项已禁用-OriginalGriff [/edit]



[edit]Code block added, "Ignore HTML..." option disabled - OriginalGriff[/edit]

推荐答案

index1i可能不存在同步(我不能肯定地说,因为您没有显示index1初始化值),因此bu1[i]未设置为对象引用.
Probably index1 and i are out of sync (I cannot say that for sure because you didn''t show index1 initialization value) hence bu1[i] is not set to an object reference.


首先,值是什么的index1?为什么要与i一起使用它来引用bu1的相同元素?他们在步吗?

为什么要使用can_Count作为循环终止条件,而不检查其是否小于或等于bu1.Length?

我猜想错误发生在行
Firstly, what is the value of index1? Why are you appearing to use it in conjuction with i to reference the same element of bu1? Are they in step?

Why are you using can_Count as your loop termination condition, but not checking that this is lower or equal to bu1.Length?

I am guessing that the error occurs on the line
bu1[index1] = new Button();

上,这表明index1 已经在bu1的范围之外.

在行

which would indicate the index1 is already outside the bound of bu1.

Put a breakpoint on the line

bu1[index1] = new Button();

上放置一个断点,然后运行程序.弄清楚您的各种变量值应该是什么,然后检查它们.如果可以,请单步执行重复检查,直到发现错误为止.如果不是您想的那样,找出原因吧!

Then run your program. Work out in your head what the various variables values should be, then check them. If they are ok, single step through repeating the checks until you spot the error. If they aren''t what you think they should be, find out why not!


我想问题出在bu1 [i]中-您在大多数地方都使用index1,然后在事件处理程序附件.我从1开始,index1最有可能从0开始.因此,您实际上正在尝试访问尚未创建的下一个按钮.
可能的解决方案:
1)使用bu1 [index1].点击+ = ...
2)bu1 [i-1].单击+ =....(对此不确定(取决于初始index1值))
I suppose the problem is in bu1[ i ] - you use index1 in most places and then i in event handler attachment. i starts from 1, index1 most likely from 0. So you are actually trying to access next button which is not created yet.
Possible solutions:
1) use bu1[index1].Click += ...
2) bu1[i - 1 ].Click += .... (not sure about this one, depends on initial index1 value)


这篇关于按钮单击事件中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆