2012-02-14 90 views
1

我目前正在開發留言系統,我需要管理員刪除特定的日誌。問題是我試圖刪除它時出現錯誤。c#Datalist刪除特定行。

的錯誤是:Index was outside the range. It may not be negative and must be less than the crowd size. Parameter name: index

我的代碼:asp.net

<asp:DataList ID="guestBookDataList" runat="server" ondeletecommand="guestBookDataList_DeleteCommand"> 
    <ItemTemplate> 
     <div id="guest-books"> 
      <span class="guestBook-Id"> # <%#DataBinder.Eval(Container.DataItem, "id") %></span><span class="guestBook-Name">Name: <%#DataBinder.Eval(Container.DataItem, "Name") %> </span> 
      <span class="guestBook-Date"> Date: <%#DataBinder.Eval(Container.DataItem, "Date") %> </span> <br /> 
      <span class="guestBook-Text"> <%#DataBinder.Eval(Container.DataItem, "text") %> </span> 
      <asp:LinkButton ID="LinkButtonDelete" CssClass="gastbok-remove" runat="server" CommandName="Delete">Delete<%#DataBinder.Eval(Container.DataItem, "id") %></asp:LinkButton> 
     </div>     
    </ItemTemplate> 
</asp:DataList> 

我的LinkBut​​ton是在數據列表的每個項目的刪除按鈕。

,這就是給我的錯誤我的C#代碼:

protected void guestBookDataList_DeleteCommand(
    object source, DataListCommandEventArgs e) 
{ 
    int id = Convert.ToInt32(guestBookDataList.DataKeys[e.Item.ItemIndex]); 
    db.deleteGeustBookLog(id); //calls the sql command 
    bindList(); 
} 

Basiclly我只是需要從DATABSE retrive的guestbooklogs ID,所以我可以將其刪除。

一直在嘗試很多不同的方法,並使用谷歌搜索這個,但我不能得到它的工作。所以現在我在問你。謝謝你的時間。

回答

2

將CommandArgument添加到帶有ID的LinkBut​​ton中。然後在刪除代碼中,查找e.CommandArgument,然後傳遞該值。

<asp:LinkButton id="LinkButton2" 
     Text="Delete" 
     CommandName="Delete" 
     CommandArgument='<%#DataBinder.Eval(Container.DataItem, "id") %>' 
     OnCommand="DeleteGuestBookEntry" 
     Runat="server"/> 

你也可以給它一個commandName,像「DeleteGuestBookEntry」或其他東西。

void DeleteGuestBookEntry(Object sender, CommandEventArgs e) 
    { 
    int id = Convert.ToInt32(e.CommandArgument); 
    db.deleteGeustBookLog(id); //calls the sql command 
    bindList(); 
    } 

我會經常檢查,以確保您的ID不爲空,且數值等,並添加一些錯誤處理,但是這是降濁辦法做到這一點。 :)

+0

AHH太感謝你了。你救了我的一天:)。它工作完美 – dumbel 2012-02-14 23:33:33

+0

你能接受答案嗎? – 2012-02-15 17:45:05

0

你應該設置 「的DataKeyNames」 屬性

<asp:DataList ID="guestBookDataList" runat="server" ondeletecommand="guestBookDataList_DeleteCommand" datakeynames="id">