Search code examples
sql-serverwpfframeworksgridcell

Getting value from a DataGrid cell in Wpf framework with a nested for loop


I cannot get value of cells in any way, because framework Wpf doesn't have Grid.Row[] property. Please help me, I cannot do anything. This is my code:

for (int i = 0; i < 8; i++)
{
    for (int j = 0; j < count; j++)
    {
        TextBlock x = (TextBlock)Grid.Columns[0].GetCellContent(Grid.Items[j]);
        MessageBox.Show(x.Text);
        string query = "UPDATE Data SET Name='" + x.Text + "'";

        SqlCommand cmd1 = new SqlCommand(query, con);

        SqlDataReader da1 = cmd1.ExecuteReader();
        da1.Close();
    }
}

The count represents the number of rows in my grid and the 8 represents the rows in the grid.

Ty for the help.


Solution

  • Let's say your datagrid is named dgrPeople and it is bound to a collection of Person objects.

    You may be able to approach it this way without casting to controls depending on what you're binding to.

    foreach (var item in dgrPeople.ItemsSource)
    {
        Person person = (Person)item;
        MessageBox.Show(person.Name);
    }