I'm currently developing a guestbook system, and I need admins to remove specific logs. The problem is I'm getting an error when trying to delete it.
The error is: Index was outside the range. It may not be negative and must be less than the crowd size.
Parameter name: index
My code: 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>
My linkbutton is the delete button for each item in the datalist.
And my C# code that's giving me the error:
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 I just need to retrive the guestbooklogs ID from the databse so I can delete it.
Been trying a lot of different methods and googling about this but I can't get it to work. So now I'm asking you. Thanks for your time.
Best Answer
Add a CommandArgument to the LinkButton with the ID of it. Then in the delete code, look for e.CommandArgument, and pass that value instead.
You could also give it a commandName like "DeleteGuestBookEntry" or something.
I'd always check to make sure that your ID is not null, and is numeric, etc, and add some error handling, but that's the down and dirty way to do it. :)