Reputation: 115
The following is the code to delete a row from Grid View and update the Content list thereby. But it gives Index out of range exception.
The designer code of Grid view is here.
<asp:GridView ID="GridViewD" runat="server" AlternatingRowStyle-BackColor="RoyalBlue" CssClass="Grid" AutoGenerateColumns="false" OnRowCancelingEdit="Cancel_Edit" OnRowDeleting="GridViewD_RowDeleting" OnRowEditing="Edit_Row" OnRowUpdating="Update_Row">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Cellphone" HeaderText="Contact" />
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:Label ID="lbldata" runat="server" Text=""></asp:Label>
Here is the code behind.
protected void GridViewD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
GridViewRow row = GridViewD.Rows[e.RowIndex];
string itemId;
itemId = ((TextBox)row.Cells[0].Controls[0]).Text;
// itemId = GridViewD.DataKeys[e.RowIndex].Value.ToString();
DeleteRow(itemId);
Bind_Data();
}
catch (Exception ex)
{
}
}
private void DeleteRow(string itemId)
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("Advertisement");
SPListItem item = null;
item = list.GetItemById(int.Parse(itemId));
web.AllowUnsafeUpdates = true;
item.Delete();
list.Update();
web.AllowUnsafeUpdates = false;
}
}
}
Index out of range exception.
How to resolve it ?
Upvotes: 0
Views: 1212
Reputation: 93
I think your itemId
is getting null
number. Please put breakpoint and check the itemId
is getting correct value or not.
You can try to change your template into item template and use the following method to get the value.
GridViewRow row = GridViewD.Rows[e.RowIndex];
Label itemIdLabel = (Label)row.FindControl("YourLabelNameitemtemp");
string itemId = itemIdLabel.Text;
Hope this help.
Upvotes: 1