2

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.

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;
            }
        }




    }

How to resolve it ?

  • 1
    Where is the error? Which line? Please provide additional feedback so that others can understand the precise problem. – Tanmay Nov 18 '15 at 5:06
  • While initializing itemid. It is giving error that index is out of range – Shahroz Shaikh Nov 18 '15 at 5:08
3

This error exception is thrown mostly when you try accessing an item at an index that isn't present. The best way to resolve the issue is to debug and check the length of the array or the data table indexes and then see whether you are deleting the correct index or not.

As per described in the comments below you would need to mention the column index that you would want to delete with the itemId = GridViewD.DataKeys[e.RowIndex].Value[0].ToString(); statement.

| improve this answer | |
  • I have debug it. but how to figure that where is the correct index ? – Shahroz Shaikh Nov 18 '15 at 5:26
  • I feel that the item index that you are passing is creating a problem. First of all check the whether the index of the row that you want to delete exists in the the data table and does it match the index of the row that you are trying to delete. – Mancy Desaee Nov 18 '15 at 6:09
  • e.RowIndex is correct but it is throughing exeption at itemId = GridViewD.DataKeys[e.RowIndex].Value.ToString(); – Shahroz Shaikh Nov 18 '15 at 6:16
  • Please elaborate on what you are trying to say. I am unable to get it. – Mancy Desaee Nov 18 '15 at 6:18
  • GridViewRow row = GridViewD.Rows[e.RowIndex]; In this e.RowIndex is 4 But at itemId = GridViewD.DataKeys[e.RowIndex].Value.ToString(); it is showing negative index. – Shahroz Shaikh Nov 18 '15 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.