Get Primary key on Row Command (GridView)

Some days back I got a query from one of my fellow, regarding a very normal situation I mean that’s the day to day task that we as a developers are doing. Here is the scenario


Scenario:
Consider you have a data grid view which show a list of products from northwind database and you want a link button which will edit the same grid view entry but in a separate page and on separate form with the help of the primary key which you may want to send to another page using query string or else.
So the task is to get the primary key of the row on which the link button is pressed.

Solution:
Well, we can achieve this task from variety of methods. Let me just give you a quick list of how we can do this.

1. Have Hidden Field in Link button column
2. Pass PK in command argument
3. Using Data key names.

Ok, for basics I have created two pages one if default.aspx which holds the grid and the other is editform.aspx which will get the primary key sent by Default.aspx

On editForm.aspx add the following code on page load. 

   1: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   2:   If Not Request.QueryString(”Id”) Is Nothing Then ‘check if there is nothing in query string
   3:       Response.Write(”Product Id Is : ” + Request.QueryString(”Id”).ToString()) ‘print the id
   4:   End If
   5: End Sub 

Now for the for the different approaches let’s read below

Approach 1 (Hidden field)

Write the following grid view on default.aspx


   1: <asp:GridView ID=”GridView1runat=”serverAutoGenerateColumns=”FalseDataSourceID=”SqlDataSource1>
   2: <Columns>
   3: <asp:BoundField DataField=”ProductNameHeaderText=”ProductName/>
   4: <asp:BoundField DataField=”QuantityPerUnitHeaderText=”QuantityPerUnit/>
   5: <asp:BoundField DataField=”UnitPriceHeaderText=”UnitPrice/>
   6: <asp:TemplateField>
   7: <ItemTemplate>
   8: <asp:HiddenField ID=”hfKeyrunat=”serverValue=’<%#Eval(”ProductID”) %>‘ />
   9: <asp:LinkButton ID=”EditCommandName=”edtrunat=”server>Edit</asp:LinkButton>
  10: </ItemTemplate>
  11: </asp:TemplateField>
  12: </Columns>
  13: </asp:GridView>  

 

Notice that, we have taken a hidden field just in the same column we have the link button and have it default value of out primary key field. Now on RowCommandEvent of the grid view write the following code

   1: Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
   2:    If e.CommandName.ToLower() = “edt”  Then
   3:       Dim lb As LinkButton = CType(e.CommandSource, LinkButton) ‘getting clicked link button
   4:       Dim strKey As String = CType(lb.Parent.FindControl(”hfKey”), HiddenField).Value ‘getting PK Value
   5:       Response.Redirect(”EditForm.aspx?id=” + strKey) ‘redirecting
   6:    End If
   7: nd Sub  

I guess code does not need any explanation, so let’s move on to the next approach.

Approach 2

We have a minor change the in Template Field of the Gridview we write in Default.aspx. replace that with the following code.


   1: <asp:TemplateField>
   2: <ItemTemplate>
   3: <asp:LinkButton ID=”EditCommandName=”edtCommandArgument=’<%#Eval(”ProductId”) %>‘ runat=”server>Edit</asp:LinkButton>
   4: </ItemTemplate>
   5: </asp:TemplateField>

So, we have remove the hidden field we have added in the last approacha and simply add the command argument to the link button, now to catch the command argument and send it to edit form write the following code onRowCommand Event 

   1: Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As  System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
   2:     If e.CommandName.ToLower() = “edt” Then
   3:        Dim strKey As String = e.CommandArgument  ’Getting Pk Value from argument
   4:        Response.Redirect(”EditForm.aspx?id=” + strKey) ‘redirecting
   5:     End If
   6: End Sub  

Approach 3:

Ok, for this you need to add DataKeyNames Property to main GridViewMarkup. In other word, it is an attribute of grid view which can accept multiple values using “,” but in our case we are using one. So when we add this attribute our grid markup will look like as follows


   1: <asp:GridView ID=”GridView1runat=”serverAutoGenerateColumns=”FalseDataKeyNames=”ProductIDDataSourceID =”SqlDataSource1>
   2: <Columns>
   3: <asp:BoundField DataField=”ProductNameHeaderText=”ProductName/>
   4: <asp:BoundField DataField=”QuantityPerUnitHeaderText=”QuantityPerUnit/>
   5: <asp:BoundField DataField=”UnitPriceHeaderText=”UnitPrice/>
   6: <asp:TemplateField>
   7: <ItemTemplate>
   8: <asp:LinkButton ID=”EditCommandName=”edtrunat=”server>Edit</asp:LinkButton>
   9: </ItemTemplate>
  10: </asp:TemplateField>
  11: </Columns>
  12: </asp:GridView>

Notice that we have remove command argument from link button, now add the following code on the RowCommand Function.

   1: Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
   2:     if e.CommandName.ToLower() = “edt” Then
   3:        Dim lb As LinkButton = CType(e.CommandSource, LinkButton)
   4:        Dim gvRow As GridViewRow = lb.BindingContainer ‘Getting current row to get index
   5:        Dim strKey As String = GridView1.DataKeys(gvRow.RowIndex)(0).ToString()
   6:        Response.Redirect(”EditForm.aspx?id=” + strKey) ‘redirecting
   7:     End If
   8: End Sub

In the above code we are getting the current row from which the link button is clicked because we need the index of the row to get the data key name value.

So, now you have plenty of choices to select which approach you like to go with :) .

Screen Cast : http://tinyurl.com/5fuj8e

Published Thursday, January 08, 2009 9:11 PM by aghausman12
Filed under: , , ,

Comments

# Link Listing - January 9, 2009

Friday, January 09, 2009 7:33 AM by Christopher Steen

ASP.NET Get Primary key on Row Command (GridView) [Via: aghausman12 ] Alternate way to select ASP.NET...

# Link Listing - January 9, 2009

Friday, January 09, 2009 7:34 AM by Christopher Steen

Link Listing - January 9, 2009

# re: Get Primary key on Row Command (GridView)

Friday, January 09, 2009 9:57 AM by holywolfv

DataKeys property can save more than one key field with ',' splitter,for instance DataKeys="ID,Name,Sex",I think it's more useful

# Get Primary key on Row Command (GridView) - Agha Usman

Saturday, January 10, 2009 10:42 PM by Web Development Community

You are voted (great) - Trackback from Web Development Community

# re: Get Primary key on Row Command (GridView)

Saturday, January 24, 2009 8:47 PM by ...

Great site.

# re: Get Primary key on Row Command (GridView)

Wednesday, February 11, 2009 5:03 PM by clueless coward

Thank you for the very timely help -- I have dealt with this previously, but could not remember the magic ingredient (DataKeyNames) that made it work.

# re: Get Primary key on Row Command (GridView)

Friday, May 08, 2009 8:28 AM by Nabeel Khan

This is an excellent post Agha Usman.

# re: Get Primary key on Row Command (GridView)

Thursday, May 14, 2009 3:42 AM by x

How to assign the primary key value to a parameter instead of redirecting it?

As an example,i need to update data in a row of a gridview by autogenerateedit in gridview. How do I assign the primary key value to the parameter in my query string?

# re: Get Primary key on Row Command (GridView)

Tuesday, October 20, 2009 12:28 AM by Vince

Thx !!!!

# re: Get Primary key on Row Command (GridView)

Tuesday, October 20, 2009 6:36 PM by Chris

Hi,

Lovely piece of work. Don't suppose you have examples in C#.

Cheers

# re: Get Primary key on Row Command (GridView)

Friday, November 27, 2009 3:13 AM by lokeshkumarn

Thank you

# re: Get Primary key on Row Command (GridView)

Friday, December 11, 2009 8:15 PM by Pat

I agree, this is an excellent post.

# re: Get Primary key on Row Command (GridView)

Tuesday, December 29, 2009 10:22 AM by yasir butt

very nice

great work

# re: Get Primary key on Row Command (GridView)

Thursday, January 13, 2011 11:04 AM by Ray K. Ragan

Agha,

The hiddenfield method worked great. Thanks!

Ray

# re: Get Primary key on Row Command (GridView)

Thursday, January 20, 2011 5:19 AM by sanket kambli

thanks a lot..ur third option worked for me...awesome

# Gridview1 rowcommand | Johnbyk

Tuesday, January 03, 2012 5:20 AM by Gridview1 rowcommand | Johnbyk

Pingback from  Gridview1 rowcommand | Johnbyk

Leave a Comment

(required) 
(required) 
(optional)
(required)