2013-03-07 184 views
1

我想要刪除我的asp.net ListView中的一個條目,它不適用於我的代碼。我如何刪除ListView中的項目?

我的代碼:

protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e) 
     { 

      if (e.CommandName == "Delete") 
      { 
       int index = Convert.ToInt32(e.CommandArgument); 

       int listcount = ListView.Items.Count; 

       if (listcount - 1 == index) 
       { 
        ListView.Items.RemoveAt(index); //go do ListView_Deleting 
       } 

      } 

     } 

     protected void ListView_SelectedIndexChanging(object sender, EventArgs e) 
     { 
      // 
     } 

     protected void ListView_Deleting(object sender, EventArgs e) 
     { 
      // 
     } 

我的aspx:

<div class="InputControlBox"> 
      <asp:ListView ID="ListView" runat="server" OnItemCommand="ListView_ItemCommand" 
      OnSelectedIndexChanging="ListView_SelectedIndexChanging" OnItemDeleting="ListView_Deleting"> 
       <LayoutTemplate> 
        ... 
       </LayoutTemplate> 
       <ItemTemplate> 
        ... 
       </ItemTemplate> 
      </asp:ListView> 
     </div> 

哪裏錯誤?

+0

什麼不工作?異常,只是不刪除? – jAC 2013-03-07 09:40:26

+0

沒有例外...只是沒有刪除:( – Tarasov 2013-03-07 09:43:56

+1

'listcount - 1 =='索引' - 這是不是意味着你只能刪除ListView中的最後一項? – barc0de 2013-03-07 10:00:36

回答

6

侑可以使用代碼

if (e.CommandName == "Delete") 
     { 
      int index = Convert.ToInt32(e.CommandArgument); 

      int listcount = ListView.Items.Count; 

      if (listcount - 1 == index) 
      { 
       dataTable.Rows[index].Delete(); 

       ListView.datasource = datatable; 
       ListView.DataBind(); 
      } 

     } 

其中數據表上,您綁定到你的ListView數據源。