简体   繁体   中英

WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?

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

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());
}

Thank you for any help!

**Edit:

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.

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);
}

EDIT:

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;

    ...

dg is your XAML DataGrid x:Name

    for (int i = 0; i < dg.Items.Count; i++)
    {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);
            for (int j = 0; j < dg.Columns.Count; j++)
            {
                TextBlock cellContent = dg.Columns[j].GetCellContent(row) as TextBlock;
                Console.WriteLine(cellContent.Text);
            }
    }

尝试使用Grid.Column[x].GetCellContent(Row[y])方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM