Click here to Skip to main content
15,885,651 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hello :)

I have a grid view, which contain a button in each row

I want to do something with the data key (the primary key ) of the grid when I press a button in some row

can I retrieve the data key for used row to use it in my C# code ?


thank you all :)
Posted

1 solution

You should bind the field into the CommandArgument of the button.
for example on the gridview, you can have a button like this one:

XML
<asp:TemplateField HeaderText="custom column">
           <asp:Button runat="server" CommandArgument='<%# Eval("UserID") %>' OnClick="OnMyButtonClick"/>
       </asp:TemplateField>


note this button is on a TemplateField. And is using evaluation the UserID into the CommandArgument property.

Now in the C# code behind you can do this:

C#
protected void OnMyButtonClick(object sender, EventArgs e)
   {
       Button b = sender as Button;
       if (b!=null)
       {
           var hey = b.CommandArgument;//this is my value!
           //do something now!
       }
   }


And voila..

Hope it helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900