Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - No Datakey on Gridview RowDeleting event!

I have a GridView just 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>

Here is how I am creating my DataTable, which the GridView is bound to, so that you know what data I am 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, oh, why are there no keys passed in the EventArgs of the RowDeleting event? I need to remove the record from the ADO.NET DataTable that I am keeping in session state when this event is fired.

Why isn't this working? Is it that DataKeys only work when using a DataSource control?

like image 314
Ronnie Overby Avatar asked Jan 23 '23 19:01

Ronnie Overby


2 Answers

This 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"] = "[email protected]";
    students.Rows.Add(student);

    return students;
}

protected void gvwStudents_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    string id = this.gvwStudents.DataKeys[e.RowIndex].Value.ToString();   
}
like image 111
Phaedrus Avatar answered Feb 01 '23 20:02

Phaedrus


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

like image 34
Phoenix Avatar answered Feb 01 '23 18:02

Phoenix