如何从WPF中的DataGrid获取所有行 [英] How to get all the rows from DataGrid in WPF
本文介绍了如何从WPF中的DataGrid获取所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在WPF应用程序中有一个DataGrid,我想通过单击按钮来获取列表中的所有行值。我尝试了一些方法,但只获得了最后一行的值...
I have a DataGrid in my WPF application, I want to get all the row values in a list in a button click. I tried some ways but I get the last row values only...
private async void Save_Btn_Click(object sender, RoutedEventArgs e)
{
pojo rowdata = new pojo();
int rowcount = calendarmstrDG.Items.Count;
List<pojo> pojolist = new List<pojo>();
var rows = (calendarmstrDG).SelectedItems;
for (int i = 1; i < rowcount - 1; i++)
{
pojo sda = (pojo)calendarmstrDG.SelectedItems;
pojolist.Add(sda);
}
}
在这里calendarmstrDG是我的datagrid名称...
pojo是我的模型类名称...
Here calendarmstrDG is my datagrid name ... pojo is my model class name ...
public class pojo
{
public string Prefix { get; set; }
public int Year { get; set; }
public int Quarter { get; set; }
public int SerialNo { get; set; }
public string From { get; set; }
public string To { get; set; }
public string PeriodName { get; set; }
}
推荐答案
使用 foreach
循环:
foreach(pojo p in calendarmstrDG.Items)
{
// do something with "p", e.g. access properties: p.SerialNo
}
DataGrid.Items集合包含类型为<$的元素c $ c> object ,因此在 foreach
循环中,我们必须指定确切的类型 pojo
能够访问属性
DataGrid.Items collection contains elements of type object
, so in foreach
loop we have to specify exact type pojo
to be able to access properties
如果您需要获取 pojo
的新列表,可以使用Linq:
if you need to get a new list of pojo
, it can be done with Linq:
List<pojo> list = calendarmstrDG.Items.OfType<pojo>().ToList();
这篇关于如何从WPF中的DataGrid获取所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文