WPF DataGrid:如何在DataGrid中迭代获取行和列? [英] WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?
问题描述
如何在C#中使用 Forms DataGridView
How can you iterate in the rows and columns of a WPF DataGrid like with a Forms DataGridView in C#?
例如,如果您有Form 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< Foo>
:
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屋!