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

时间:2009-02-24 21:57:48

标签: asp.net data-binding gridview ado.net datatable

我有一个像这样的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>

以下是我创建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;
}

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

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

3 个答案:

答案 0 :(得分: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();   
}

答案 1 :(得分:1)

将GridView控件的DataKeyNames属性设置为数据主键的名称。

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

答案 2 :(得分:0)

添加

<asp:BoundField DataField="ID" />

并查看该字段是否有值。