迭代数据网格的行 [英] iterating through rows of a datagrid
问题描述
我试图从数据网格中提取值,通过遍历数据网格的所有行
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);
}
但它是给我DataRow drv中的InvalidCastException。
有人可以告诉我应该做些什么改变,这样做有效吗?
datagrid有一个绑定,它正在由ms sql 2008数据库存储过程填充
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
推荐答案
使用 DataGridRow 不是 DataRow 它们是不同的对象
Use a DataGridRow not a DataRow they are a different objects
foreach (DataGridRow drv in PGIPortfolio.Items)
然而不清楚在这个上下文中的Items是什么。假设PGIPortfolio是DataGridView,那么你的循环应该写成
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)
编辑
我假设您在WinForms中使用DataGridView控件WPF DataGrid
在这种情况下,正确的方法是使用ItemsSource属性。
请尝试此代码....
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)
{
.....
}
}
}
这篇关于迭代数据网格的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!