0

我是WPF的初学者。我正在尝试使用 DataRow/DataRowView 读取 Datagrid Selected Items。我的代码如下 -

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

但我面临以下错误 -

“无法将类型为 '<>f__AnonymousTypeb 11[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]' 的对象转换为类型 'System.Data.DataRowView ’。”

当我尝试使用以下方式时,效果很好-

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

问题是当我需要添加新列/更改数据网格列位置时,我需要更改整个分配值的索引。为了解决这个问题,我想用上面提到的方式用列名赋值。

4

3 回答 3

1

SelectedItems 列表的内容将是绑定到 DataGrid 的类型。因此,例如,如果我的代码隐藏中有一个属性 List DataSource,并且我将此列表绑定为数据网格的 ItemsSource:

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

grid.SelectedItems 将返回一个字符串列表。

在您的情况下,DataGrid 的 ItemsSource 绑定到某种匿名类型。虽然我通常不鼓励在这种特殊情况下使用匿名类型,但您的解决方法如下:

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

需要换???使用匿名类中的属性名称,其中包含您要放入 txtPhotoIDNo 的数据。

于 2016-04-02T11:30:42.343 回答
0

最后我发现了我的问题。那就是我的 SelectedItems 的两个值是 null。因此,键值对没有完美地准备。以下代码完美运行。

foreach (System.Data.DataRowView row in dgDocument.SelectedItems)
  {
    txtPhotoIDNo.Text = row["PhotoIdNumber"].ToString();
  }
于 2016-04-02T20:23:24.080 回答
0
 foreach (dynamic row in dgBarDetails.ItemsSource)
 { 
  myList.Add(row);
 }

在我的例子中,row 是我的类的一个对象,用于填充 ItemsSource。它可以是 int 或 string 或您在 ItemsSource 中的任何内容

于 2016-11-30T22:29:27.947 回答