C# – Retrieving all GridViewRow objects from a GridView control with paging enabled

asp.netcgridviewpaging

I currently have a GridView control on my aspx page with paging enabled and I need to loop through the entire row collection/count to process the selected records. With my current code, it will only loop through the current page of GridView row.

What is the best way to accomplish this task?

Here is my current code:

ASPX page:

<asp:GridView ID="MyGridView" runat="server" AllowPaging="true" PageSize="20">
   <Columns>
      <!-- My Column list -->
   </Columns>
</asp:GridView>
<asp:Button id="MyButton" runat="server" Text="Add" OnClick="MyButton_Click" />  

code behind:

protected void MyButton_Click(object sender, EventArgs e)
{
    for (int Count = 0; Count < MyGridView.Rows.Count; Count++)
    {
        //The row count is 20 and only contains the GridViewRow object in the current page view  
        //I want to retrieve the all GridViews rows so I can add them to a ReorderList control
    }   
}

Best Answer

Yes because your gridview UI is only aware of the current page. Get the datasource and determine the row count from there...

        int count = ((DataTable)MyGridView.DataSource).Rows.Count;

//or

        int count = ((ICollection<SomeRecord>)MyGridView.DataSource).Count;
Related Topic