0

我根据一些运行时变量的值创建了一些按钮(我什至不知道有多少)。

我的按钮代码如下:

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(';');
    }

但是,单击按钮时,单击方法不会启动。我想这与我在运行时构建按钮的事实有关。Cld有人建议如何让这种方法启动?

谢谢, Ondrej

4

1 回答 1

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";        
}
于 2012-05-09T11:39:21.737 回答