Delete Gridview row when paging is enabled

a 夏天 提交于 2019-12-11 09:28:55

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/28870762/delete-gridview-row-when-paging-is-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!