Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...