Monday, December 6, 2010

How to get DataKey in GridView's OnRowCommand event

/// <summary>
/// Handle grid Employee row command
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void grdEmployee_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int index = row.RowIndex;
int EmployeeID = Convert.ToInt32(grdEmployee.DataKeys[index].Value);
}
}

Here “e.CommandSource” is the Clicked LinkButton and NamingContainer is its Parent Control. So that will be the GridViewRow. Here we can easily find the DataKey. Here in my Example EmployeeID is the DataKey

<asp:GridView ID="grdEmployee" runat="server"
EmptyDataText="No Employee Available."
Width="100%" AllowPaging="True"
PageSize="10" OnRowDeleting="grdEmployee_RowDeleting" OnPageIndexChanging="grdEmployee_PageIndexChanging"
DataKeyNames="EmployeeID"
OnRowCommand="grdEmployee_OnRowCommand">
<Columns>
<asp:BoundField HeaderText="Employee Code" DataField="EmployeeCode">
</asp:BoundField>
<asp:BoundField HeaderText="Employee Name" DataField="EmployeeName">
</asp:BoundField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="lbtnDelete" runat="server" CausesValidation="false" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" CausesValidation="false" CommandName="Details" Text="View Details"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

1 comment: