将事件附加到动态创建的按钮单击

时间:2012-09-28 02:14:42

标签: c# asp.net event-handling

我想将事件附加到在运行时生成的单击按钮。直到这一点,我已经编写了代码,但无法将按钮的ID传递给方法。这是我的代码

此代码没有通过任何错误,另一个问题是在click事件之后控件被冲走了。如何防止这种情况?

protected void Button1_Click(object sender, EventArgs e)
   {
     int i = int.Parse(TextBox1.Text);
     for (int x = 1; x <= i; x++)
     {
       Button b = new Button();
       b.ID = "btn_" + x.ToString();
       b.Text = "btn_" + x.ToString();
       b.Click += new System.EventHandler(myEventHandler);
       pnlHolder.Controls.Add(b);
     }
   }

 private void myEventHandler(object sender, EventArgs e)
 {
   txtMain.Text = sender.ToString(); // I want to know which button was pressed
 }

2 个答案:

答案 0 :(得分:2)

试,

txtMain.Text = (sender as Button).Name;

txtMain.Text = (sender as Button).Text;

答案 1 :(得分:2)

试试这个

 private void myEventHandler(object sender, EventArgs e)
 {
   Button b = (Button) sender;
   txtMain.Text = b.ID;
   //
   txtMain.Text = b.Text;

   if(b.ID == "button1")
     doThis();
   else if(b.ID == "button2")
     doThat();
 }