【问题标题】:How to get info from object in the datagrid while this object is Entity Framework object?当该对象是实体框架对象时,如何从数据网格中的对象获取信息?
【发布时间】:2019-05-24 18:02:58
【问题描述】:

我想获取所选单元格的值作为字符串。但我不能选择它作为实体框架对象。

我尝试使用不是来自实体框架的对象列表来完成它,它工作正常:

public MainWindow()
{
        InitializeComponent();

        using (SellEntities Context = new SellEntities())
        {
            var query = from t in Context.Categories
                        orderby t.Id
                        select new
                        {
                            t.Id,
                            CategoryName = t.Name
                        };
            CategoriesDataGridVeiw.ItemsSource = query.ToList();
        }
}

private void CategoriesDataGridVeiw_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
        var rows = CategoriesDataGridVeiw.SelectedItem as Category;

        if (rows != null)
        {
            MessageBox.Show(rows.Name);
        }
        else
            MessageBox.Show("Null");

        CategoriesDataGridVeiw.UnselectAll();
}

【问题讨论】:

  • 这需要minimal reproducible example。不清楚你在问什么。
  • 问题是这个变量(行)总是=空。我无法从数据网格中选择 Item 作为类别或任何由 Entity Framework 制作的类。我试图澄清我的问题,但我不知道如何描述它。
  • 嗯,很明显new { t.Id, CategoryName = t.Name } 不能转换为Category。但我不明白问题描述。 我不能选择它作为实体框架对象 -- 为什么不呢?
  • 非常感谢。你让我跟踪我的代码找到解决方案。我已经被这个问题困扰了 4 天。

标签: c# wpf entity-framework datagrid


【解决方案1】:

问题是数据网格包含查询对象,我选择数据网格中的项目作为类别。 解决方案是确保 datagrid.ItemsSource 等于您稍后要转换的内容。

CategoriesDataGridVeiw.ItemsSource = Context.Categories.ToList();

现在我可以使用它了:

CategoriesDataGridVeiw.SelectedItem as Category

谢谢https://stackoverflow.com/users/861716/gert-arnold。 你让我想到了正确的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多