WPF DataGrid:如何在 DataGrid 中迭代以获取行和列? [英] WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?

查看:31
本文介绍了WPF DataGrid:如何在 DataGrid 中迭代以获取行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像在 C# 中使用 Forms DataGridView 那样在 WPF DataGrid 的行和列中进行迭代?

How can you iterate in the rows and columns of a WPF DataGrid like with a Forms DataGridView in C#?

例如,如果您有 Forms DataGridView,您可以执行以下操作:

For example, if you have Forms DataGridView you can do something like this:

for(int i = 0; i < formsDataGrid1.Rows.Count; i++)
{
  MessageBox.Show(formsDataGrid1.Rows[i].ToString());
  for(int j = 0; j < formsDataGrid1.Columns.Count; j++)
     MessageBox.Show(formsDataGrid1.Rows[i].Cells[j].ToString());
}

感谢您的帮助!

我想这样做的原因是用户将使用 DataGrid 在 DataGrid 的第二列中输入某些信息.此外,这个 DataGrid 有多行,我希望能够获取该数据并用它更新数据库.

The reason I want to do this is that the DataGrid will be used by a user to enter certain informations in the second column of the DataGrid. Also, this DataGrid has multiple rows and I want to able to get that data and update a database with it.

推荐答案

通常情况下,您不会这样做:您访问基础数据源而不是 DataGrid 本身.例如,假设数据源是一个 IEnumerable :

Typically, you don't do that : you access the underlying data source instead of the DataGrid itself. For instance, assuming the data source is an IEnumerable<Foo> :

foreach(Foo f in foos)
{
    MessageBox.Show(f.Name);
}

<小时>

您不需要显式访问网格的特定单元格:如果网格绑定到对象列表,则当用户编辑网格中的相应单元格时,对象的属性将自动更新.

You don't need to access explicitly a specific cell of the grid : if the grid is bound to a list of objects, the object's property will be automatically updated when the user edits the corresponding cell in the grid.

带有联系人列表的简单示例:

Simple example with a list of contacts :

    public class Contact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
    ...
    ObservableCollection<Contact> contacts = new ObservableCollection<Contact>();
    dataGrid.ItemsSource = contacts;

    ...

这篇关于WPF DataGrid:如何在 DataGrid 中迭代以获取行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆