C# – WPF DataGrid: How to iterate in a DataGrid to get rows and columns

cdatagriditerationwpfwpftoolkit

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.

Best Answer

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