问题
I am trying to extract values from a datagrid, by iterating through all the rows of the datagrid
foreach (DataRow drv in PGIPortfolio.Items)
{
// DataRow row = drv.Row;
string acname = drv["Portfolio"].ToString();
string paramt = drv["Par Amount"].ToString();
MessageBox.Show(acname);
}
But it is giving me an InvalidCastException at DataRow drv. Could someone tell me what changes I should make so it works? The datagrid has a binding, and it is being populated by a stored procedure from ms sql 2008 database
回答1:
Use a DataGridRow not a DataRow they are a different objects
foreach (DataGridRow drv in PGIPortfolio.Items)
However it is not clear what Items is in this context. Assuming that PGIPortfolio is the DataGridView then your loop should be written as
foreach (DataGridRow drv in PGIPortfolio.Rows)
EDIT
I assumed that you was using the DataGridView control in WinForms, not the WPF DataGrid
In this case then the correct approach is to use the ItemsSource property.
Please try this code....
var itemsSource = PGIPortfolio.ItemsSource as IEnumerable;
if (itemsSource != null)
{
foreach (var item in itemsSource)
{
var row = PGIPortfolio.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (row != null)
{
.....
}
}
}
回答2:
foreach(DataGridViewRow r in dataGridView1.Rows)
来源:https://stackoverflow.com/questions/16863531/iterating-through-rows-of-a-datagrid