Question

I have a gridview that when more than 10 items are in the view, a new page is added, pretty straightforward...Anyway, when a user is on the second page and clicks delete on that record, the item from the first page in that row is deleted. Example: page 1 had 10 items and in the first row is say a part number 1234 and on the second page the first row has part number 7890. If the user clicks delete for the 7890 record, the 1234 record is deleted from the first row, or which ever corresponding row they select to remove.

Here's the code:

protected void griditems_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        griditems.PageIndex = e.NewPageIndex;
        BindData();
    }

EDIT Sorry everyone...here is the delete command:

 protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            DataTable dt = (DataTable)Session["table"];
            if (dt.Rows.Count > 0)
            {
                dt.Rows.RemoveAt(e.RowIndex);
                griditems.DataSource = dt;
                BindData();
            }
        }
        catch
        {
            //error message
        }
    }

In the aspx:

<asp:GridView ID="griditems" runat="server" onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing" onrowupdating="griditems_RowUpdating"
                  AllowPaging="True" PageSize="10" onpageindexchanging="griditems_PageIndexChanging" Onrowcancelingedit="griditems_RowCancelingEdit" 
                  Caption="Order Details" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" onrowdatabound="griditems_RowDataBound" >            
        <EditRowStyle BackColor="#FF9900" BorderStyle="Double"/> 
        <RowStyle HorizontalAlign="Center"/>
</asp:GridView>
Was it helpful?

Solution

You should show your griditems_RowDeleting implementation as well, but even without it I can assume that you just need to take the index of the row and add to it the page number times the amount of records in each page.

Console.WriteLine(e.RowIndex); // 7
Console.WriteLine(griditems.PageIndex); // 3

// Assuming you have 10 records per page, you can safely say...
var realIndexOfRecord = e.RowIndex + griditems.PageIndex * 10; // 37

After your edit:

protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    try
    {
        DataTable dt = (DataTable)Session["table"];
        if (dt.Rows.Count > 0)
        {
            // Replace `10` with the appropriate variable
            dt.Rows.RemoveAt(e.RowIndex + griditems.PageIndex * 10);
            griditems.DataSource = dt;
            BindData();
        }
    }
    catch
    {
        //error message
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top