ASP.NET - Gridview RowDeleting事件上没有Datakey!

Ron*_*rby 4 asp.net data-binding datatable ado.net gridview

我有一个像这样的GridView:

<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>
Run Code Online (Sandbox Code Playgroud)

以下是我如何创建GridView绑定的DataTable,以便您知道我正在处理的数据:

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;
}
Run Code Online (Sandbox Code Playgroud)

为什么哦,为什么RowDeleting事件的EventArgs中没有传递密钥?我需要从ADO.NET DataTable中删除当我触发此事件时保持会话状态的记录.

为什么这不起作用?DataKeys只在使用DataSource控件时才有效吗?

Pha*_*rus 8

这有效:

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();   
}
Run Code Online (Sandbox Code Playgroud)