"Peted" wrote:
>
Hi thanks for that.
Suppose however i do want to just iterate through a DataGrid , lets
say through the rows using a "foreach" statement. Is this possible
with a datagrid, seeing as it does not expose a datagridrows
collection.
Is there anyway to do this at all ?
thanks
Peter
Well, using reflection you can get to the DataGridRow using the following:
Type gridType = Type.GetType(@"
System.Windows.Forms.DataGrid,
System.Windows.Forms,
Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089");
PropertyInfo piRows = gridType.GetProperty("DataGridRows",
BindingFlags.Instance | BindingFlags.NonPublic);
Type rowType = piRows.PropertyType.GetElementType();
PropertyInfo piValue = rowType.GetProperty("RowNumber");
object[] rows = piRows.GetValue(myDataGrid, null) as object[];
foreach (object row in rows)
{
int rowNumber = (int)piValue.GetValue(row, null);
}
However, there are no Cells property or Value so the DataGridRow is only
meant for display and only contains the row index to the actual row, which
would explain why DataGridRows is null before display time, even though
DataSource is set.
You can instead use the indexer on the DataGrid itself to obtain the values
int numRows = dg.BindingContext[myDataGrid.DataSource].Count;
object[] data = new object[numRows];
for (int i = 0; i < numRows; i++)
{
data[i] = myDataGrid[i, 0];
}
However, the number of columns is a bit trickier as this is the number of
displayed columns, not the number of potential columns from the DataSource.
A third method is parsing through the DataSource itself, which according to
the documentations can be a DataTable, DataView, DataSet, DataViewManager,
IListSource or IList.
Once you determine which type the DataGrid.DataSource contains you can use
properties and methods on each of the six types to parse the content.
if (dg.DataSource is DataTable)
ParseTable(dg.DataSource as DataTable);
else if (dg.DataSource is IList)
ParseList(dg.DataSource as IList);
....
etc
--
Happy Coding!
Morten Wennevik [C# MVP]