Reputation: 11
I have three hyperlinks each inside list elements in an unordered list in a webform. I want to have a single function to handle all the clicks of hyperlinks. so I need to determine the id of the hyperlink which is clicked in the code behind file so that I will be able to handle the click response properly using asp.net C#. I want to have one function which will handle all the three onclick
events. In that function I want to determine the id of the hyperlink which was clicked and the basis of the id , the corresponding portion of the code will be executed in the code behind file.
<ul>
<li>
<a id="A5" href="#" onServerClick="Anchor_Click" runat="server">...</a>
</li>
<li>
<a id="A6" href="#" onServerClick="Anchor_Click" runat="server">...</a>
</li>
<li>
<a id="A7" href="#" onServerClick="Anchor_Click" runat="server">...</a>
</li>
</ul>
In the code behind file.
protected void Anchor_Click(Object sender, EventArgs e)
{
if(id=="A5")
some code
else if(id=="A6")
some code
else if(id=="A7")
some code
}
Upvotes: 0
Views: 2771
Reputation: 892
If you don't use HyperLink (which you probably don't use, since these trigger a get to the TargetUrl and not a post) but use LinkButton you can set the CommandArgument. On the OnClick you can read the CommandArgument and parse it to an int.
If your link is in an item with DataSource binding you can do this:
<asp:LinkButton ID="someLink" runat="server" CommandArgument="<%# ((YourObjectType)Container.DataItem).Id %>" OnClick="SomeLinkClicked" />
If your link is in the page itself without binding you should set the commandArgument in code-behind for the link, which should be directly accessible.
//Markup
<asp:LinkButton ID="someLink" runat="server" OnClick="SomeLinkClicked" />
//code-behind
someLink.CommandArgument = yourObject.Id
In your OnClick you can do this to get the id and trigger whatever needs to be done for this id:
protected void SomeLinkClicked(object sender, CommandEventArgs args) {
int id;
if (int.TryParse(args.CommandArgument, out id)) {
//Do something here with id
}
}
Upvotes: 1
Reputation: 2830
All ASP.NET UI element event handlers provide two parameters:
TheEventHandler(object sender, EventArgs e)
The sender represents the element that triggered the event. In your case, it would be the hyperlink. So cast it to the appropriate type (Or even just do Control to be more generic, then get the ID):
(sender as Control).ClientID
would give you the ClientID of the item clicked.
However, this only works if the element is runat="server"
If this is a true hyperlink as in just a regular old <a>
tag, there would be no way to capture the event on the server side.
Upvotes: 0