"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= b77a5c561934e08 9");
PropertyInfo piRows = gridType.GetPro perty("DataGrid Rows",
BindingFlags.In stance | BindingFlags.No nPublic);
Type rowType = piRows.Property Type.GetElement Type();
PropertyInfo piValue = rowType.GetProp erty("RowNumber ");
object[] rows = piRows.GetValue (myDataGrid, null) as object[];
foreach (object row in rows)
{
int rowNumber = (int)piValue.Ge tValue(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.BindingConte xt[myDataGrid.Data Source].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.DataSo urce contains you can use
properties and methods on each of the six types to parse the content.
if (dg.DataSource is DataTable)
ParseTable(dg.D ataSource as DataTable);
else if (dg.DataSource is IList)
ParseList(dg.Da taSource as IList);
....
etc
--
Happy Coding!
Morten Wennevik [C# MVP]