[英]How can I get row in datagrid WPF?
I would like to get all rows in order to check some rows that are the same in the database , I'm try using many solutions in StackOverlow but any of them work for me :我想获取所有行以检查数据库中某些相同的行,我尝试在 StackOverlow 中使用许多解决方案,但其中任何一个都适合我:
for (int i = 0; i < dataGrid.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
.ContainerFromIndex(i);
}
This code return value cannot be null
Exception.此代码返回
value cannot be null
异常。
I have tried also this line of code and I'm got the same Exception ( the object currentitem was null ).我也尝试过这行代码,但得到了相同的异常(对象 currentitem 为 null )。
var currentItem = myDataGrid.SelectedItem as MyObject;
Complete Code:完整代码:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
grid.ItemsSource = null;
grid.ItemsSource = work;
grid.Items.Refresh();
for (int i = 0; i < grid.Items.Count; i++) // My grid items count equals to 7
{
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(i); // this value was null
var currentItem = grid.SelectedItem as object; // this value was null
}
}
You could bind the item source of your DataGrid
to an ObservableCollection
and run a foreach
loop over it.您可以将
DataGrid
的项目源绑定到ObservableCollection
并在其上运行foreach
循环。
I think that makes things a lot easier.我认为这让事情变得容易多了。
Finally I got it , I fixed the error by using this code :最后我明白了,我使用以下代码修复了错误:
for (int i = 0; i < grid.Items.Count; i++)
{
GridModel row = (GridModel)grid.Items[i];
}
// Note : The grid model is a class for the Datagrid ( properties are the same as the columns name of the datagrid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.