您能帮我吗,我需要在循环中更改按钮的事件名称,这是怎么可能的? [英] could you please help me i need to change the event name of the button in loop how it is possible?

查看:77
本文介绍了您能帮我吗,我需要在循环中更改按钮的事件名称,这是怎么可能的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for(int i = 0; i< count; i ++)
{
字符串Qry =从tblProduct选择类别";
OleDbDataAdapter adpter =新的OleDbDataAdapter(Qry,objCon);
DataTable dt = new DataTable();
adpter.Fill(dt);

Button b = new Button();
b.Name = dt.Rows [i] [类别"] .ToString();
b.Text = dt.Rows [i] ["Category"].ToString();
b.Click + = new EventHandler(btnRetreive_Click);

b.Location = new Point(20,(i * 20));
this.Controls.Add(b);
//您还需要添加一些代码来准确调整按钮的大小和位置.你可以
//根据使用dtButtonsToCreate.Count
的控件数量来执行此操作 }

for (int i = 0; i < count; i++)
{
string Qry = "Select Category from tblProduct";
OleDbDataAdapter adpter = new OleDbDataAdapter(Qry, objCon);
DataTable dt = new DataTable();
adpter.Fill(dt);

Button b = new Button();
b.Name = dt.Rows[i]["Category"].ToString();
b.Text = dt.Rows[i]["Category"].ToString();
b.Click += new EventHandler(btnRetreive_Click);

b.Location = new Point(20, (i * 20));
this.Controls.Add(b);
//you will also need to add some code to accurately size and place the button. You can
//do that based on the amount of controls there are with dtButtonsToCreate.Count
}

推荐答案

您不能.如果您考虑一下,那就没有必要尝试了:因为事件处理程序的名称需要在编译时知道,并且需要在运行时进行更改,所以您必须设置一个几乎无限的事件处理程序.事件处理程序列表,以便处理从dataTable返回的任何数据.

而是使用事件处理程序的sender参数来确定单击了哪个按钮:
You can''t. If you think about it, it doesn''t make sense to try: Because the name of the event handler needs to be known at compile time, and you need it to change at run time, you would have to set up an virtually infinite list of event handlers in order to cope with whatever data comes back from your dataTable.

Instead, use the sender parameter of the event handler to decide which button was clicked:
private void btnRetrieve_Click(object sender, EventArgs e)
   {
   Button b = sender as Button;
   if (b != null)
      {
      switch (b.Text)
          {
          case "Category 1":
          ...
          }
      }
   }

或使用Control.Tag属性将特定值放入其中以在处理程序方法中进行处理.

Or use the Control.Tag property to put a specific value into it for processing in the handler method.


这篇关于您能帮我吗,我需要在循环中更改按钮的事件名称,这是怎么可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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