【问题标题】:ASP.NET - No Datakey on Gridview RowDeleting event!ASP.NET - Gridview RowDeleting 事件上没有数据键!
【发布时间】:2009-02-24 21:57:47
【问题描述】:

我有一个像这样的 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 控件时才有效?

【问题讨论】:

  • 我认为您应该在这个问题中添加“数据绑定”标签。顺便说一句,我一直在努力解决完全相同的问题。
  • 如何将学生添加到您的表中?在调用 Deleting 方法之前(即在 Page_Load 中),数据是否已填充到您的表中?

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


【解决方案1】:

这行得通:

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();   
}

【讨论】:

  • 难道我不能在事件 args 中访问吗?
  • 您的断言是正确的,GridViewDeletedEventArgs.Keys 集合仅在使用 DataSourceID 时才会填充。
  • 这是 GridViewDeletedEventArks.Keys 集合未填充问题的解决方法。我们是否只是放弃了这个填充?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    添加

    <asp:BoundField DataField="ID" />
    

    并查看该字段是否有值。

    【讨论】:

    • 我已经检查过了。它确实有价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多