Monday, 21 June 2010

How to find out if there are items for an EnumerableRowCollection

Unfortunately, this class doesn’t have a .Count() method, so you have to do a horrible hack to find out if there are items.

I suppose you could implement it as an Extension method, but as it is, this is what you need to do:

// Create table and populate data
DataTable dt = new DataTable();
dt.Rows.Add( new object[] { "sample1" });
// Filter by a non-existent field, so now dataRows is now an 
// EnumerableRowCollection with no rows
var dataRows = from row in dt.AsEnumerable()
               where row.Field<string>("Column1") eq "FAKE DATA"
               select row;
// This next line throws an InvalidOperationException 
//// DataTable filteredResults = dataRows.CopyToDataTable();   
// Instead, create a new IEnumerator and iterate through it manually.
IEnumerator iEnum = dataRows.GetEnumerator();
     ShowMessage("No data available");}
     DataTable filteredResults = dataRows.CopyToDataTable();   
     //   More DataTable processing here ....     
     MyGridView1.DataSource = filteredResults;     

It is nasty, but it works :-)