How to retrieve data from a DataGrid in WPF?
To grab the data in a WPF DataGrid, you can use one of the following methods:
- Use the ItemsSource property of DataGrid to retrieve the entire dataset.
var data = myDataGrid.ItemsSource as IEnumerable<MyModel>;
- Iterate through the rows and columns of the DataGrid, and fetch the data in each cell one by one.
foreach (var item in myDataGrid.Items)
{
DataGridRow row = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromItem(item);
// 获取行中的所有列数据
var cellValue1 = (row.Item as MyModel).Property1;
var cellValue2 = (row.Item as MyModel).Property2;
// ...
// 或者通过列索引获取特定列的数据
var cellValue3 = (row.Item as MyModel)[3];
}
Please note that the second method can only retrieve the currently visible rows. If you need to retrieve data from all rows, you may need to first scroll to the bottom and then iterate through rows beyond the visible ones.
I hope this information is helpful to you!