ASP.NET - No Datakey at Gridview RowDeleting Event!

I have a gridview like this:

<asp:GridView ID="gvwStudents" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ShowHeader="False" onrowdeleting="gvwStudents_RowDeleting"> <Columns> <asp:BoundField DataField="FirstName" /> <asp:BoundField DataField="LastName" /> <asp:BoundField DataField="Email" /> <asp:CommandField ShowDeleteButton="True" DeleteText="Remove" /> </Columns> </asp:GridView> 

This is how I create my DataTable, with which the GridView is connected, so that you know what data I'm dealing with:

 private DataTable MakeStudentsTable() { DataTable students = new DataTable(); DataColumn ID = students.Columns.Add("ID", typeof(int)); ID.AutoIncrement = true; DataColumn firstName = students.Columns.Add("FirstName", typeof(string)); DataColumn lastName = students.Columns.Add("LastName", typeof(string)); DataColumn email = students.Columns.Add("Email", typeof(string)); return students; } 

Why and why there are no keys passed to RowDeleting eventArgs? I need to delete a record from DataTable ADO.NET, which I save in session state when this event is fired.

Why is this not working? Does DataKeys only work when using a DataSource control?

+4
source share
3 answers

It works:

 private DataTable MakeStudentsTable() { DataTable students = new DataTable(); DataColumn ID = students.Columns.Add("ID", typeof(int)); ID.AutoIncrement = true; DataColumn firstName = students.Columns.Add("FirstName", typeof(string)); DataColumn lastName = students.Columns.Add("LastName", typeof(string)); DataColumn email = students.Columns.Add("Email", typeof(string)); DataRow student = students.NewRow(); student["FirstName"] = "foo"; student["LastName"] = "bar"; student["Email"] = " foo@bar.com "; students.Rows.Add(student); return students; } protected void gvwStudents_RowDeleting(object sender, GridViewDeleteEventArgs e) { string id = this.gvwStudents.DataKeys[e.RowIndex].Value.ToString(); } 
+8
source

Set the DataKeyNames property of the GridView control to the name (s) of the primary key (s) of your data.

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx

+1
source

add

 <asp:BoundField DataField="ID" /> 

and see if the field value matters.

0
source

All Articles