2009-02-24 56 views
4

我有一個GridView就這樣:ASP.NET - Gridview RowDeleting事件上沒有Datakey!

<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控件綁定到,讓你知道我處理什麼數據:

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控件時才起作用嗎?

+0

我想你應該在這個問題上加上「databinding」標籤。 順便說一句,我一直在抨擊我的頭在完全相同的問題。 – 2009-02-25 07:01:39

+0

你如何將學生添加到你的桌子?在調用Deleting方法之前(即在Page_Load中)數據是否填充到表中? – cjk 2009-02-25 11:50:45

回答

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"] = "[email protected]"; 
    students.Rows.Add(student); 

    return students; 
} 

protected void gvwStudents_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
    string id = this.gvwStudents.DataKeys[e.RowIndex].Value.ToString(); 
} 
0

添加

<asp:BoundField DataField="ID" /> 

,看看現場,甚至有一個值。

+0

我已經檢查過這個。它確實有價值。 – 2009-02-24 23:51:53

相關問題