如何从WPF中的DataGrid获取所有行

0 c# wpf datagrid

我的 WPF 应用程序中有一个 DataGrid,我想通过单击按钮获取列表中的所有行值。我尝试了一些方法,但我只得到最后一行的值......

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这里 calendarmstrDG 是我的数据网格名称... pojo 是我的模型类名称...

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; }
}
Run Code Online (Sandbox Code Playgroud)

ASh*_*ASh 5

使用循环迭代所有项目foreach

foreach(pojo p in calendarmstrDG.Items)
{
   // do something with "p", e.g. access properties: p.SerialNo 
}
Run Code Online (Sandbox Code Playgroud)

DataGrid.Items 集合包含 type 的元素object,因此在foreach循环中我们必须指定确切的类型pojo才能访问属性

如果您需要获取 的新列表pojo,可以使用 Linq 来完成:

List<pojo> list = calendarmstrDG.Items.OfType<pojo>().ToList();
Run Code Online (Sandbox Code Playgroud)