web 2.0

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 scenarioScenario: 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 column2. Pass PK in command argument3. 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.aspxOn editForm.aspx add the following code on page load. 
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load   If Not Request.QueryString("Id") Is Nothing Then 'check if there is nothing in query string       Response.Write("Product Id Is : " + Request.QueryString("Id").ToString()) 'print the id   End IfEnd Sub 
Now for the for the different approaches let's read belowApproach 1 (Hidden field)Write the following grid view on default.aspx 
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  DataSourceID="SqlDataSource1"><Columns><asp:BoundField DataField="ProductName" HeaderText="ProductName" /><asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /><asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /><asp:TemplateField><ItemTemplate><asp:HiddenField ID="hfKey" runat="server" Value='<%#Eval("ProductID") %>' /><asp:LinkButton ID="Edit" CommandName="edt" runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField></Columns></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 
 Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    If e.CommandName.ToLower() = "edt"  Then       Dim lb As LinkButton = CType(e.CommandSource, LinkButton) 'getting clicked link button       Dim strKey As String = CType(lb.Parent.FindControl("hfKey"), HiddenField).Value 'getting PK Value       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub  
I guess code does not need any explanation, so let's move on to the next approach.Approach 2We have a minor change the in Template Field of the Gridview we write in Default.aspx. replace that with the following code.  
<asp:TemplateField><ItemTemplate><asp:LinkButton ID="Edit" CommandName="edt" CommandArgument='<%#Eval("ProductId") %>' runat="server">Edit</asp:LinkButton></ItemTemplate></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   
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As  System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    If e.CommandName.ToLower() = "edt" Then       Dim strKey As String = e.CommandArgument  'Getting Pk Value from argument       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd 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
 
 
 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID ="SqlDataSource1"><Columns><asp:BoundField DataField="ProductName" HeaderText="ProductName" /><asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /><asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /><asp:TemplateField><ItemTemplate><asp:LinkButton ID="Edit" CommandName="edt" runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField></Columns></asp:GridView>
 
 Notice that we have remove command argument from link button, now add the following code on the RowCommand Function.
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    if e.CommandName.ToLower() = "edt" Then       Dim lb As LinkButton = CType(e.CommandSource, LinkButton)       Dim gvRow As GridViewRow = lb.BindingContainer 'Getting current row to get index       Dim strKey As String = GridView1.DataKeys(gvRow.RowIndex)(0).ToString()       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd 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

Comments

Farhan Farooqui , on 11/21/2008 12:25:46 AM Said:

Farhan Farooqui

Great ... mashaAllaha..... Allaah will give you reward for this....
you made my life easy.... you have define with every possible method....

Twahir , on 12/21/2008 7:18:10 AM Said:

Twahir

Thank you very much for this insight, i worked very hard on how to solve the problem, through try and error i later was able to  solve it but without actually knowing what im doing!, fortunately when i came accross this website, and saw that you have listed a lot of methods of how to solve this problem. Thank you so much

holywolfv , on 12/25/2008 1:22:47 AM Said:

holywolfv

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

sheartech United States, on 7/15/2009 4:11:27 PM Said:

sheartech

great this is what im looking for, you are very good in providing useful information for everyone.

evidence eliminator United States, on 8/21/2009 6:34:44 AM Said:

evidence eliminator

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

get your spouse back United States, on 8/22/2009 12:52:19 AM Said:

get your spouse back

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

wrinkle creams United States, on 8/22/2009 10:38:15 AM Said:

wrinkle creams

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Linda Mirano United States, on 8/30/2009 5:03:54 AM Said:

Linda Mirano

You may have not intended to do so, but I think you have managed to express the state of mind that a lot of people are in. The sense of wanting to help, but not knowing how or where, is something a lot of us are going through.

Linda Mirano United States, on 8/30/2009 5:05:42 AM Said:

Linda Mirano

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

Oprah superfood United States, on 9/6/2009 2:16:20 AM Said:

Oprah superfood

Pretty Interesting post. Couldnt be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this post to him. Pretty sure he will have a good read. Thanks for sharing!

Reverse Phone Lookup United States, on 9/16/2009 9:59:24 PM Said:

Reverse Phone Lookup

Never seen such cool post. I read it all the way to the end. Keep them coming.

anonymous proxy Thailand, on 9/28/2009 1:33:36 PM Said:

anonymous proxy

Great insights. I loved to read your article. You must be putting a lot of time into your blog!

proxy Thailand, on 9/29/2009 4:31:13 PM Said:

proxy

Great share. Keep up the good work.

IR35 rules United States, on 10/2/2009 12:00:31 AM Said:

IR35 rules

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

ผลบอล Thailand, on 10/4/2009 12:08:43 AM Said:

ผลบอล

This is a very nice post.

unblock myspace , on 10/4/2009 2:26:04 PM Said:

unblock myspace

Great blog, this could be the best blog I ever visited thi month. Never stop to write something useful dude!.

Ggler United States, on 10/11/2009 6:50:05 AM Said:

Ggler

Nice post. I love it.

โปรแกรม , on 10/28/2009 1:20:17 AM Said:

โปรแกรม

Easily, the article is in reality the sweetest on this deserving topic. I fit in with your conclusions and will eagerly look forward to your future updates. Just saying thanks will not just be adequate, for the great lucidity in your writing. I will directly grab your rss feed to stay abreast of any updates.

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading