Reputation: 465
I have A|B|C|D.....|Z link buttons on web forms . Now i have to add single event in code behind to handles all link buttons. How to do with C# asp.net
Upvotes: 1
Views: 5417
Reputation: 10747
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;
}
Upvotes: 2
Reputation: 18290
Associate the eventhandler of these Buttons or LinkButtons at Page_Init and check the sender control that made the request.
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.
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)
{
..
}
Upvotes: 2
Reputation: 393
If you didn't mean on dynamicaly setting events, you just set the same ethod in OnClick event for all buttons:
<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. Then, in code behind method signature, you should set CommandEventArgs instead of EventArgs.
Upvotes: 2