我想将事件附加到运行时生成的按钮。到目前为止,我已经编写了代码,但无法将按钮的 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
}
尝试,
txtMain.Text = (sender as Button).Name;
或
txtMain.Text = (sender as Button).Text;
试试这个
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();
}