Search code examples
c#asp.netgridviewdatatablepagination

Delete Gridview row when paging is enabled


I have a Gridview with paging enabled and delete button enabled. With the below code the row above the one for which the delete button is pressed gets deleted. I have also tried doing "dt.Rows.Remove(dt.Rows[rowIndex-1]".

The row values are in a DataTable only (not in Database).

Stuck badly

Need help or code to delete row when paging is enabled in gridview.

protected void GVRequest_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;

                GVRequest.DataSource = dt;
                GVRequest.DataBind();

                for (int i = 0; i < GVRequest.Rows.Count - 1; i++)
                {
                    GVRequest.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                //SetPreviousData();

                dt.AcceptChanges();

                ViewState["CurrentTable"] = dt;

                DataView view = new DataView(dt);
                DataTable dt1 = view.ToTable( /*distinct*/ true, "CartonID", "FileID", "FileMasterID", "DeptFileID", "RequestID");

                GVRequest.DataSource = dt1;

                DataBind();
            }
        }

Solution

  • From OP comments

    when I press the delete button it is deleting a selected row from the first page only

    When you are going to delete record from page after first page, you have to add the records on previous pages to get the index of the record in the DataTable as the DataTable does not know on what page you are.

    With the code you have if you delete record at index 4 on second page you will actually delete record with index 4 on first page.

    You need to calculate the index of DataTable keeping the PageNo and PageSize in expression as shown under.

    int rowIndex = e.RowIndex + GVRequest.PageIndex * GVRequest.PageSize ;
    

    Note: I assume PageNo is zero for first page