4

我有一个像这样的 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 数据表中删除记录。

为什么这不起作用?DataKeys 是否仅在使用 DataSource 控件时才有效?

4

3 回答 3

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();   
}
于 2009-02-25T06:31:42.540 回答
1

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

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

于 2016-09-02T15:18:11.130 回答
0

添加

<asp:BoundField DataField="ID" />

并查看该字段是否有值。

于 2009-02-24T22:23:33.850 回答