views:

1648

answers:

1

Hello! 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.

A: 

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;

    ...
Thomas Levesque
Like the ItemsSource?
Partial
How do you get the DataSource for a WPF toolkit Datagrid?
Partial
Yes, the ItemsSource
Thomas Levesque
Can you show a more detailed example?
Partial
see my updated answer
Thomas Levesque