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



我正在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 
}

我如何制作一个事件,当你点击按钮时,你会进入一个功能,我怎么能知道哪个按钮被点击了,并让我进入了我的功能。谢谢

您执行

 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中添加控件。

希望这对你有用。

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"来确定是哪个控件发送了请求。

不要设置按钮的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;
    }
}

相关内容

  • 没有找到相关文章

最新更新