遍历数据网格的行
本文关键字:网格 数据网 数据 遍历 | 更新日期: 2023-09-27 18:16:14
我试图从数据网格中提取值,通过迭代数据网格的所有行
foreach (DataRow drv in PGIPortfolio.Items)
{
// DataRow row = drv.Row;
string acname = drv["Portfolio"].ToString();
string paramt = drv["Par Amount"].ToString();
MessageBox.Show(acname);
}
但它给了我一个InvalidCastException在DataRow驱动。有人能告诉我我应该做些什么改变才能奏效吗?数据网格有一个绑定,它由ms sql 2008数据库
使用DataGridRow而不是DataRow,它们是不同的对象
foreach (DataGridRow drv in PGIPortfolio.Items)
然而,在这个上下文中不清楚Items是什么。假设PGIPortfolio是DataGridView,那么你的循环应该写成
foreach (DataGridRow drv in PGIPortfolio.Rows)
编辑我假设你在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)
{
.....
}
}
}
foreach(DataGridViewRow r in dataGridView1.Rows)