代码之家  ›  专栏  ›  技术社区  ›  Ronnie Overby

ASP.NET-Gridview行删除事件上没有数据键!

  •  4
  • Ronnie Overby  · 技术社区  · 15 年前

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

    下面是我如何创建我的DataTable(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;
    }
    

    为什么这不起作用?是否只有在使用数据源控件时数据键才起作用?

    3 回复  |  直到 15 年前
        1
  •  8
  •   Phaedrus    15 年前

    这项工作:

    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();   
    }
    
        2
  •  1
  •   Phoenix    8 年前

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

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

        3
  •  0
  •   Al W    15 年前

    添加

    <asp:BoundField DataField="ID" />
    

    并查看该字段是否有值。