从动态创建的按钮数组中识别单击的按钮 [英] identify a clicked button from a dynamically created button array

查看:73
本文介绍了从动态创建的按钮数组中识别单击的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将这些按钮创建为动态按钮数组时,如何确定它们是否被单击?

问题
列中有一组按钮,这些按钮是通过for循环(动态)创建的.
单击列的第二个按钮.如何识别用户是否单击了第二个按钮?

how can we identify a button whether it is clicked or not,when those buttons are created as dynamic button array?

Question
there are set of buttons in a column which are created from a for loop(dynamically).
2nd button of the column is clicked.how can we identify that the user has clicked the 2nd button?

{
 x = 30;
 for (int i = 0; i < ar.Length; i++)
 {
     bu[index1] = new Button();
     bu[index1].Location = new Point(50, x);
     bu[index1].Size = new Size(75, 20);
     bu[index1].Text = "1";
     bu[index1].Name = b+ i;
     bu[index1].Click += new EventHandler(button_Click1);
     x = x + 100;
     index1++;
 }
 this.Controls.AddRange(bu);
}

private void button_Click1(object sender, EventArgs e)
{
     if(bu[0].Name=="b0")
     MessageBox.Show("selected rw1");
     else if(bu[1].Name=="b1")
     MessageBox.Show("selected rw2";

}


上面的代码无法正常运行,如Question.中所述.有没有人可以帮我解决这个问题?


above code is not working expected as explained in the Question.can any one help me to correct this??

推荐答案

您有sender参数可用,请使用它.例如:

You have the sender argument available, use it. For instance:

private void button_Click1(object sender, EventArgs e)
{
  Button selected = sender as Button;
  MessageBox( selected.Name);
}


bu[index1].Name = "b" + i;
不要忘记引号! (不过,除非您碰巧有一个名为b的字符串或数字变量存在,否则您的编译器应该会发现该错误.)
在处理程序中,您需要检查实际单击的按钮的名称((Button)sender).如果bu是全局数组,则还可以在处理程序中的bu中查找发件人,以发现被单击的按钮的索引.
bu[index1].Name = "b" + i;
Don''t forget the quotes! (Your compiler should be picking that mistake up though unless you happen to have a string or numeric variable called b lying around.)

In the handler you need to be checking the name of the button that was actually clicked ((Button)sender). If bu is a global array you could also look for sender in bu in the handler to discover the index of the button that was clicked.


这篇关于从动态创建的按钮数组中识别单击的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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