【问题标题】:Unable to cast object of type AnonymousType To System.Data.DataRowView in WPF无法在 WPF 中将 AnonymousType 类型的对象转换为 System.Data.DataRowView
【发布时间】:2016-07-22 04:21:16
【问题描述】:

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

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

但我面临以下错误--

“无法转换类型的对象 '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]' 键入“System.Data.DataRowView”。”

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

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

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

【问题讨论】:

  • DataGrid 控件与System.Data / DataTable 等无关。SelectedItems 属性包含您添加到网格中的实际对象(在这种情况下似乎是匿名类型)。您应该研究数据绑定 - 您不应该尝试像这样直接设置文本。
  • 拜托!举个例子吧。

标签: c# wpf datagrid datarow datarowview


【解决方案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 的数据。

【讨论】:

    【解决方案2】:

    我终于找到了我的问题。那就是我的 SelectedItems 的两个值是空的。因此,键值对没有完美地准备。以下代码完美运行。

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

    【讨论】:

      【解决方案3】:
       foreach (dynamic row in dgBarDetails.ItemsSource)
       { 
        myList.Add(row);
       }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-14
        • 1970-01-01
        • 1970-01-01
        • 2013-07-10
        • 2012-01-23
        • 2014-10-07
        • 1970-01-01
        相关资源
        最近更新 更多