0

I want to get the data every column from a datagrid connected to an Entity Framework database. I want to cast them to their respective Textboxes but I can't seemingly draw the data from the datagrid.

Here's the code I am using at first (saw it here on SO):

 private void DataGridCamiao_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataGrid DataGridCamiao = sender as DataGrid;
        DataRowView row = (DataRowView)DataGridCamiao.SelectedItems[0];
        TextBoxMarca.Text = row["Marca"].ToString();
    }

Though after running it gives me an error:

System.InvalidCastException: Cannot associate (my custom type) to DataRowView

I've read about it and I've changed it to my custom type, to which it says it can't be indexed and does not run, which basically left me stumped as I tried other methods. I'd like some insight on what I'm doing wrong here, maybe different ways to achieve the same goal and I forwardly thank anyone trying to help me out.

Gonçalo
  • 35
  • 5

2 Answers2

0

You should cast the SelectedItem property to your entity type:

private void DataGridCamiao_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid DataGridCamiao = sender as DataGrid;
    if (DataGridCamiao.SelectedItem != null)
    {
        var item = DataGridCamiao.SelectedItem as YourEntityClass;
        if (item != null)
            TextBoxMarca.Text = item.Marca;
    }
}

Change YourEntityClass to the name of your entity type, i.e. the type T of the IEnumerable<T> that you have set or bind to the ItemsSource property of the DataGrid.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Oh goodness, thank you so much. It worked now, and it's been killing my head for the past 72 hours. Thanks so much for helping an underslept college student :p – Gonçalo Jun 20 '17 at 10:48
0

you can do the same without code-behind:

<DataGrid Name="DataGridCamiao">
    <!--columns, attributes, etc here-->
</DataGrid>

<TextBox Name="TextBoxMarca" 
         Text="{Binding Path=SelectedItem.Marca, ElementName=DataGridCamiao}"/>

and it is even better to switch to MVVM approach and bind both DataGrid.SelectedItem and TextBox.Text to view model properties.

ASh
  • 34,632
  • 9
  • 60
  • 82