WPF的DataGrid:你如何在DataGrid迭代获得的行和列? [英] WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?
问题描述
你怎么能在的行和列迭代一个 WPF的DataGrid 像一个在C#中
How can you iterate in the rows and columns of a WPF DataGrid like with a Forms DataGridView in C#?
例如,如果您有窗体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屋!