0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Osman
  • 1,270
  • 2
  • 16
  • 40
  • 1
    The `DataGrid` control has nothing to do with `System.Data` / `DataTable` etc. The `SelectedItems` property contains the actual objects you have added to the grid (which in this case seem to be anonymous types). You should look into data binding - you shouldn't be trying to set the text directly like this. – Charles Mager Apr 02 '16 at 10:26
  • Please! Give me an example. – Osman Apr 02 '16 at 10:50

3 Answers3

1

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.

Nick Sologoub
  • 724
  • 1
  • 7
  • 21
0

At Last I found my Problem. That is two Values of my SelectedItems was null.For this reason Key value pair does not prepare perfectly. The following code work perfectly.

foreach (System.Data.DataRowView row in dgDocument.SelectedItems)
  {
    txtPhotoIDNo.Text = row["PhotoIdNumber"].ToString();
  }
Osman
  • 1,270
  • 2
  • 16
  • 40
0
 foreach (dynamic row in dgBarDetails.ItemsSource)
 { 
  myList.Add(row);
 }

in my case row is an object of my class used to populate ItemsSource. It can be an int or string or whatever you have in ItemsSource

Bianca Kalman
  • 229
  • 4
  • 3