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

9 Comments

Comments have been disabled for this content.