1

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

这段代码没有出现任何错误,另一个问题是点击事件后控件被冲走。如何防止这种情况?

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
 }
4

2 回答 2

2

尝试,

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

或者

txtMain.Text = (sender as Button).Text;
于 2012-09-28T02:17:21.610 回答
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();
 }
于 2012-09-28T02:18:23.040 回答