Return an ID from a LinkButton

I needed to pass the ID of a record that was bound to an ASP.NET LinkButton to the code behind page. Though there are other ways to do it, this is the way that worked for me. First, the GridView control that held the LinkButton, having removed other controls for clarity:

 <asp:GridView ID="grdLocations" DataKeyNames="ID" runat="server">
                <asp:LinkButton ID="lnkViewLocation" CommandArgument='<%#Bind("ID")%>' OnClick="ViewLocation_Click" Text='<%#Bind("Name")%>' runat="server" />

 Secondly, the code behind. I just casted the sender object as a LinkButton and was able to get the CommandArgument from the LinkButton:

 protected void ViewLocation_Click(object sender, EventArgs e)
LinkButton MyButton = (LinkButton)sender;
Int64 LocationId = Convert.ToInt64(MyButton.CommandArgument.ToString());
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: