[英]How to handle single event for multiple Link button in c# asp.net
I have A|B|C|D.....|Z link buttons on web forms . 我在Web表单上有A | B | C | D ..... | Z链接按钮。 Now i have to add single event in code behind to handles all link buttons.
现在,我必须在代码中添加单个事件,以处理所有链接按钮。 How to do with C# asp.net
如何使用C#asp.net
Use like : 使用方式如下:
button1.Click += new EventHandler(Button_Click);
button2.Click += new EventHandler(Button_Click);
button3.Click += new EventHandler(Button_Click);
......
That would subscribe all the events to the single event handler. 那会将所有事件订阅到单个事件处理程序。 You can get which button has been clicked on event handler :-
您可以获取事件处理程序上单击了哪个按钮:-
private void Button_Click(object sender, System.EventArgs e)
{
Button b = (Button) sender;
Label1.Text = b.ID;
}
If you didn't mean on dynamicaly setting events, you just set the same ethod in OnClick event for all buttons: 如果您不是要动态设置事件,则只需在OnClick事件中为所有按钮设置相同的方法即可:
<asp:LinkButton id="btnA" Text="A" runat="server" OnClick="myMethod" />
<asp:LinkButton id="btnB" Text="B" runat="server" OnClick="myMethod" />
in code behind: 在后面的代码中:
potected void myMethod(object sender, EventArgs e)
{
....
}
This should work... 这应该工作...
Also, instead of OnClick, you could set CommandName and additionaly set CommandArgument for each LinkButton, to pass different parameters. 另外,可以为每个LinkButton设置CommandName并另外设置CommandArgument来代替OnClick,以传递不同的参数。 Then, in code behind method signature, you should set CommandEventArgs instead of EventArgs.
然后,在方法签名后面的代码中,应设置CommandEventArgs而不是EventArgs。
Associate the eventhandler of these Buttons or LinkButtons at Page_Init and check the sender control that made the request. 在Page_Init上将这些Button或LinkButtons的事件处理程序关联起来,并检查发出请求的发送者控件。
protected void Page_Init()
{
LinkButton1.Click += Link_Click;
LinkButton2.Click += Link_Click;
LinkButton3.Click += Link_Click;
LinkButton4.Click += Link_Click;
}
cast the control according to your postback enabled controls either it is button or linkbutton and check for some control perperty of that control to identify that control. 根据启用了回发功能的控件(是button或linkbutton)来投射控件,并检查该控件的某些控件性能以识别该控件。
private void Link_Click(object sender, EventArgs e)
{
LinkButton button = sender as LinkButton;
if (button.Text == "LinkButton1")
{
Response.Write("<script>alert('link1');</script>");
}
else if (button.Text == "LinkButton2")
{
Response.Write("<script>alert('link2');</script>");
}
}
you can check for the control as: 您可以通过以下方式检查控件:
Button button = (Button)sender;
if(button is Button1)
{
..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.