我根据某些运行时变量的值创建一些按钮(我甚至不知道有多少)。
我的按钮代码如下:
Button cancel = new Button();
cancel.Text = "Cancel";
cancel.ID = "cancelEnrollmentForStudent" + zapsanePredmetyList.ElementAt(i).ID.ToString() + "-" + i ;
cancel.Click += new EventHandler(cancelEnrollment);
string toCancel = selectedSubject.SelectedValue + ";" + studentToEnroll.SelectedValue;
cancel.CommandArgument = toCancel;
而click方法的代码是
protected void cancelEnrollment(object sender, EventArgs e)
{
//do something when button clicked.
Button sourceButton = (Button)sender;
string[] data = sourceButton.CommandArgument.Split(';');
}
但是,单击该按钮时,单击方法不会启动。我想这与事实有关,我在运行时构建了按钮。有人建议如何启动这种方法吗?
谢谢, 的Ondrej
答案 0 :(得分:0)
您必须重写OnInit,在OnInit方法中添加代码。
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Button btn = new Button();
btn.ID = "btn1";
btn.Text = "Button1";
btn.Click += new EventHandler(btn_Click);
this.form1.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
bt.Text = "Changed";
}