C# 遍历数据网格的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16863531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iterating through rows of a datagrid
提问by user2415339
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
但它在 DataRow drv 给了我一个 InvalidCastException。有人可以告诉我应该进行哪些更改以使其有效吗?数据网格有一个绑定,它由来自 ms sql 2008 数据库的存储过程填充
回答by Steve
Use a DataGridRownot a DataRowthey are a different objects
使用DataGridRow而不是DataRow它们是不同的对象
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
然而,不清楚在这种情况下 Items 是什么。假设 PGIPortfolio 是 DataGridView 那么你的循环应该写成
foreach (DataGridRow drv in PGIPortfolio.Rows)
EDITI 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....
编辑我假设您在 WinForms 中使用 DataGridView 控件,而不是 WPF DataGrid 在这种情况下,正确的方法是使用 ItemsSource 属性。
请试试这个代码....
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)
{
.....
}
}
}
回答by user2852297
foreach(DataGridViewRow r in dataGridView1.Rows)
foreach(DataGridViewRow r in dataGridView1.Rows)

