Friday, December 30, 2011

Select record in gridview

After heavy usage of different ways of selecting record in a gridview i have realized to post them in the blog

1) Use of DataKeyName and CommandField

Insert a command field in grid, for simplicity I have shown a select button

<asp:CommandField ShowSelectButton="True">
<ItemStyle Font-Size="Small" Width="5%" />
asp:CommandField>

and provide datakeyname in definition of grid as

<asp:GridView ID="grdCustomers" runat="server" Width="90%" DataKeyNames="pk_Id"
AutoGenerateColumns="False" AllowSorting="True">

It will provide access to following values on SelectedIndexChanged of grid or other events

grdCustomers.SelectedDataKey.Value
grdCustomers.SelectedRow
Easy First One!

2) Using a TemplateField

Insert a template field in appropriate position among gridview columns and add a Link Button like below

<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select" CommandArgument=>asp:LinkButton>

Notice the attributes in it, 'CommandName' which is any unique name and 'CommandArgument' where PK_ID is a column name in datasource, you all know about eval dont you?

Now in code behind add a RowCommand event for gridview where you may use the following code

If e.CommandName = "Select" Then
Dim pk_id As String = e.CommandArgument
End If

To select gridview row in this case use this line:
Dim Dim row As GridViewRow = CType(CType(e.CommandSource, LinkButton).NamingContainer, GridViewRow)

Use it and enjoy your experience with ASP.NET gridview!