views:

2474

answers:

2

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
    }   
}
+1  A: 

I think you should get the row count from your data source's row count.

If you need to filter rows, you can use DataTable's / DataView's Select method.

EDIT : You can not get actual row count by gridview.Rows.Count if gridview is paged. Depending on your comment, I assume that you're using listDataSource generic list to bind your gridview, you can get your row count as :

List<DataSourceItem> selectedRows = 
  listDataSource.FindAll(delegate(DataSourceItem item)
  {
      // Assuming you have a IsSelected bool property 
      // that refers your row is selected : 
      return item.IsSelected;
  });
  int rowCount = selectedRows.Count;
Canavar
I am using a generic list of my custom class as my GridView's data source
Michael Kniskern
Also, I need to add the selected records from this GridView and append them to an Ajax Control tool kit ReorderList control.
Michael Kniskern
I update my answer, you can use selectedRows generic list for your ReorderList control.
Canavar
+1  A: 

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;
CRice
I get an "Object reference not set to an instance of an object" exception when I use this code in my button click event.
Michael Kniskern
Probably because when you are referencing it the object is no longer available. You could try saving the count in ViewState at the time you assign the datasource to the gridview (using the above), and retrieve it when required again (in button click).
CRice