/// <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>
Dot net Sample codes, C#.net, ASP.net, VB.NET, Dot net Tips, Data grid, Grid View, Dot net Framework, SQL Server
Showing posts with label DataKey. Show all posts
Showing posts with label DataKey. Show all posts
Monday, December 6, 2010
Friday, October 8, 2010
DataKey from a GridView RowCommand Event
Method to get DataKey from a GridView RowCommand Event
protected void grdEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int index = row.RowIndex;
int employeeID = Convert.ToInt32(grdEmployees.DataKeys[index].Value);
}
}
For this eg: There should be GridView Control with a TemplateField and that should contain a Linkbutton with CommandName="Select"
protected void grdEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int index = row.RowIndex;
int employeeID = Convert.ToInt32(grdEmployees.DataKeys[index].Value);
}
}
For this eg: There should be GridView Control with a TemplateField and that should contain a Linkbutton with CommandName="Select"
Subscribe to:
Posts (Atom)