Search code examples
c#wpfdatagriddatarowdatarowview

Unable to cast object of type AnonymousType To System.Data.DataRowView in WPF


I am beginner in WPF. I am trying to read Datagrid Selected Items with DataRow/DataRowView. My code is following--

foreach (System.Data.DataRowView row in dgDocument.SelectedItems)
  {
    txtPhotoIDNo.Text = row["PhotoIdNumber"].ToString();
  }

but I am facing the following error--

"Unable to cast object of type '<>f__AnonymousTypeb11[System.String,System.Byte,System.String,System.String,System.String,System.Byte[],System.Nullable1[System.DateTime],System.String,System.Nullable`1[System.DateTime],System.String,System.String]' to type 'System.Data.DataRowView'."

When I am trying with following Way, that works fine-

(dgDocument.SelectedCells[2].Column.GetCellContent(item) as TextBlock).Text;

The problem is when I required to add a new column/change the datagrid column position, I required to change index for entire assigned value. To cover this problem, I want to assign value with the above mentioned way with column Name.


Solution

  • The content of SelectedItems list is going to be of the type that is bound to your DataGrid. So for example if I have a property List DataSource in my codebehind and I bind this list to be the ItemsSource of the data grid:

    <DataGrid x:Name="grid" ItemsSource={Binding DataSource) />
    

    the grid.SelectedItems will return me a List of strings.

    In your case the ItemsSource of the DataGrid is bound to some kind of anonymous type. While I would generally discourage from using anonymous types in this particular case, the workaround for you would be the following:

    foreach (dynamic item in dgDocument.SelectedItems)
      {
        txtPhotoIDNo.Text = Convert.ToString(item.???);
      }
    

    You need to substitute ??? with the name of the property from the anonymous class that contains the data you are looking to put into txtPhotoIDNo.