哪个按钮引发了onclick事件?

时间:2011-05-06 19:39:18

标签: c# asp.net events

我创建了3 LinkButton他们都有相同的onclick事件,现在我必须找到哪个按钮调用onclick事件并且它是ID

<asp:LinkButton ID="LinkButton1" runat="server" onclick="lnk_Click"/> 
<asp:LinkButton ID="LinkButton2" runat="server" onclick="lnk_Click"/> 
<asp:LinkButton ID="LinkButton3" runat="server" onclick="lnk_Click"/> 

4 个答案:

答案 0 :(得分:3)

当然来自发件人对象:

LinkBut​​ton btn =(LinkBut​​ton)sender;

btn.ID

protected void MyBtnHandler(Object sender, EventArgs e)
{
     LinkButton btn = (LinkButton)sender;
          switch (btn.CommandName)
          {
                case "ThisBtnClick":
                    DoWhatever(btn.CommandArgument.ToString());
                    break;
                case "ThatBtnClick":
                    DoSomethingElse(btn.CommandArgument.ToString());
                    break;
           }
}

答案 1 :(得分:1)

将发件人投放到LinkButton,然后您可以从中获取所点击按钮的ID。

LinkButton lb = (LinkButton)sender;
string ID = lb.ID; //the id of the button that was clicked

答案 2 :(得分:1)

你可以做到

LinkButton lb = sender as LinkButton;

然后访问它的属性。但是,如果你的逻辑差别很大,那么分成多个处理程序可能是个好习惯。

答案 3 :(得分:1)

你的功能应该是“发件人”object

void lnk_Click(object sender, EventArgs e)
{
    LinkButton btn = sender as LinkButton;

    if (btn != null)
    {
        String id = btn.ID;
        //etc
    }
}