为多个按钮创建事件并知道单击了哪个按钮

时间:2012-02-01 17:03:47

标签: asp.net button event-handling

我正在asp.net中编写一个Web应用程序, 在后面的代码中我有这段代码:

foreach(UserDetails _UD in m_TeachersDetailsList)     
{
  Button button = new Button();// a Button control
  button.Text = "click";
  button.ID = "SelectedTeacher";
  TableCell tableCell = new TableCell();// a Cell control
  tableCell.Controls.Add(button);
  TableRow tableRow = new TableRow();
  tableRow.Cells.Add(tableCell); // a table row
  TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx 
}

如何制作一个事件,当您点击按钮进入某个功能时, 我怎么知道哪个按钮被点击并带我到我的功能。 谢谢。

3 个答案:

答案 0 :(得分:1)

你这样做

 int id = 0;
 foreach(UserDetails _UD in m_TeachersDetailsList)     
 {
    Button button = new Button();// a Button control
    button.Text = "click";
    button.ID = "selectedTeacher" + id++;
    TableCell tableCell = new TableCell();// a Cell control
    tableCell.Controls.Add(button);
    TableRow tableRow = new TableRow();
    tableRow.Cells.Add(tableCell); // a table row
    TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx 
    button.Click += new EventHandler(this.button_Click);
 }

常见的事件处理程序

protected void button_Click(object sender, EventArgs e)
{
    //This way you will get the button clicked
    Button button = (Button)sender;

}

重要

您需要在OnInit

中添加控件

希望这适合你。

答案 1 :(得分:1)

不要设置按钮的id,让它默认。改为设置按钮的CommandArgument属性:

foreach (UserDetails _UD in m_TeachersDetailsList)     
{
  Button button = new Button();// a Button control
  button.Text = "click";
  button.CommandArgument = _UD.UserDetailID.ToString(); // some unique identifier

  // this is optional, if you need multiple actions for each UserDetail:
  button.CommandName = "SomeAction"; // optional

  button.Command += new EventHandler(detailButton_Handler);

  // ...etc...
}

然后您的处理程序需要检查CommandNameCommandArgument值:

public void detailButton_Handler(object sender, EventArgs e)
{
    string DetailID = e.CommandArgument.ToString();
    switch (e.CommandName.ToString())
    {
        case "SomeAction":
        /// Now you know which Detail they clicked on
            break;

        case "OtherAction":
            break;
    }
}

答案 2 :(得分:0)

ASPX

asp:Button ID="btnTest" runat="server" onclick="btn_Click" 

代码隐藏

protected void btn_Click(object sender, EventArgs e)
{
    Button mybutton = (Button)sender;
    Response.Write(mybutton.ID);
}

只需使用btn_Click作为每个按钮的onclick。然后使用“sender”确定发送请求的控件。