Home > Blockchain >  How to get the selected Row values in TextBoxes for DataGrid in WPF C#
How to get the selected Row values in TextBoxes for DataGrid in WPF C#

Time:10-15

I want to display a selected row out of the datagrid into some textboxes. The problem is that it becomes null at line 4 when converting into a DataRowView. Why is this?

1 private void dataGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
2    {
3        DataGrid grid = (DataGrid)sender;
4        DataRowView selected_row = grid.SelectedItem as DataRowView;
5
6        if (selected_row != null)
7        {
8            comboBoxCategory.Text = selected_row["Category"].ToString();
9            textBoxBrand.Text = selected_row["Brand"].ToString();
10            textBoxName.Text = selected_row["Name"].ToString();
11            textBoxCount.Text = selected_row["Count"].ToString();
12            textBoxPrice.Text = selected_row["Price"].ToString();
13       }
14    }

enter image description here

enter image description here

CodePudding user response:

Apparantly the SelectedItem property doesn't return a DataRowView.

Either cast to the appropriate type assuming you have define one, or use the dynamic keyword:

private void dataGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid grid = (DataGrid)sender;
    dynamic selected_row = grid.SelectedItem;

    comboBoxCategory.Text = selected_row.Categorie.ToString();
    textBoxBrand.Text = selected_row.Merk.ToString();
    textBoxName.Text = selected_row.Naam.ToString();
    textBoxCount.Text = selected_row.Aantal.ToString();
    textBoxPrice.Text = selected_row.Prijs.ToString();
}
  • Related