Various ways of using DataKeyNames in Gridview in Dot Net.

Posted by vishalneeraj-24503 under ASP.NET category on | Points: 40 | Views : 1308
Suppose we have a Gridview like below:-
and we have taken DataKeyNames as id,and employee_code

<asp:GridView ID="grid_view_employee_details" runat="server" AllowPaging="true" PageSize="5" AutoGenerateColumns="false" DataKeyNames="employee_id,employee_code" OnRowCommand="grid_view_employee_details_RowCommand">
<asp:Button ID="btn_delete" runat="server" CommandName="Delete" Text="Delete" />

On the Row_Command event,i will get employee_id and employee_code as:-

protected void grid_view_employee_details_RowDeleting(object sender, GridViewDeleteEventArgs e)
//1st way by passing column_name as string in Values
int employee_id1 = Convert.ToInt32(grid_view_employee_details.DataKeys[e.RowIndex].Values["id"]);
string employee_code1 = Convert.ToString(grid_view_employee_details.DataKeys[e.RowIndex].Values["employee_code"]);

//2nd way by passing column index as integer in Values
int employee_id2 = Convert.ToInt32(grid_view_employee_details.DataKeys[e.RowIndex].Values[0]);
string employee_code2 = Convert.ToString(grid_view_employee_details.DataKeys[e.RowIndex].Values[1]);

//3rd way by using only Value property not Values
int employee_id3 = Convert.ToInt32(grid_view_employee_details.DataKeys[e.RowIndex].Value);

If we have taken on one column name in DataKeyNames, then value property will work,
But it there are more than 1 column in DataKeyNames,then Values property will work.
And 1 more important things,
Always use Column name not index, if someone has changed column index, then your code will not work.

Comments or Responses

Login to post response