2013-08-27 26 views
1

我的GridView上有一個刪除按鈕。點擊刪除按鈕後,該行應完全從會話中刪除 。我目前做如下:從數據集中完全刪除一行

protected void gvMainLog_RowCommand(Object sender, GridViewCommandEventArgs e) 
    { 
     if (e.CommandName == "Remove") 
     { 

      GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer); 
      int rowindex = rowSelect.RowIndex; 

      DataSet ds = ((DataSet)Session["old"]); 

      ds.Tables[0].Rows[rowindex].Delete(); 

      Session["old"] = ds; 

      gvMainLog.DataSource = Session["old"]; 
      gvMainLog.DataBind(); 

     } 

的問題是:

ds.Tables[0].Rows[rowindex].Delete(); 

僅刪除該行中的內容。當我看數據集時,它顯示一個空行。

有沒有辦法刪除整行,沒有顯示空行?

+1

你試過datarow.Remove()嗎? http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.remove.aspx – Zaki

+0

你可以試試[Remove](http://msdn.microsoft.com/en-us/library/ DataRowCollection對象的system.data.datarowcollection.remove.aspx)方法。 – GunnerL3510

回答

7

嘗試調用

ds.AcceptChanges() 
row.Delete後

()。

7

如果你想刪除一個單一的數據行,RemoveAt移除是更容易的選擇:

ds.Tables[0].Rows.RemoveAt(rowIndex); 

奧斯卡的答案也是正確的,根據remarks for RemoveAt on MSDN

當行被刪除,該行中的所有數據都會丟失。您也可以調用DataRow類的Delete方法來標記要刪除的行。調用RemoveAt與調用Delete並調用AcceptChanges相同。

+1

對我來說,它是.RemoveAt(rowIndex),而不是。刪除 – Krondorian

+0

@ Krondorian謝謝你指出這一點。我相應地編輯了我的答案。 Remove和RemoveAt都具有同樣的行爲;這些方法之間的唯一區別是您必須傳遞的參數才能確定要刪除的行。 – User