将 LINQ 查询绑定到 DataGridView [英] Binding LINQ query to DataGridView

查看:21
本文介绍了将 LINQ 查询绑定到 DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很令人困惑,我使用 AsDataView 将查询结果绑定到 dgv,它在以下情况下工作正常:

This is very confusing, I use AsDataView to bind query result to a dgv and it works fine with the following:

var query = from c in myDatabaseDataSet.Diamond where c.p_Id == p_Id select c;
dataGridView1.DataSource = query.AsDataView();

然而,这会导致错误:

var query = from item in myDatabaseDataSet.Items
    where item.p_Id == p_Id
    join diamond in myDatabaseDataSet.Diamond
        on item.p_Id equals diamond.p_Id
    join category in myDatabaseDataSet.DiamondCategory
        on diamond.dc_Id equals category.dc_Id
    select new
    {
        Product = item.p_Name,
        Weight = diamond.d_Weight,
        Category = category.dc_Name
    };

    dataGridView1.DataSource = query.AsDataView();

错误:

Instance argument: cannot convert from
'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 
'System.Data.DataTable'

AsDataView 没有出现在查询中.(列表).为什么会发生这种情况?那么如何将上面的查询绑定到 dgv?.

AsDataView doesn't show up in query.(List). Why is this happen? How to bind the query above to the dgv then?.

推荐答案

AsDataView 如下:

public static DataView AsDataView(
    this DataTable table
)

唯一的参数是 DataTable.

您的查询返回一个匿名的 IEnumerable没有隐式转换为 DataTable 的类型(或一系列 DataRow 实例,在这种情况下,您可以使用它来帮助您创建 DataTable).

The query you have is returning an IEnumerable of an anonymous type which doesn't have an implicit conversion to a DataTable (or a sequence of DataRow instances, in which case you could use that to help you create a DataTable).

您需要将结果返回到 DataTable 或可以转换为 DataTable 的内容中,然后它就会起作用.

You need to get the results back into a DataTable or something you can convert into a DataTable and then it will work.

在您的特定情况下,您似乎曾经(或正在)使用 类型化数据集.如果是这种情况,那么您应该能够获取选择的值,然后创建新的类型化 DataRow 实例(应该有适合您的工厂方法),然后可以将其放入类型化的 DataTable 中,可以在其上调用 AsDataView.

In your particular case, it seems that you were (or are) using typed DataSets. If that is the case, then you should be able to take the values that were selected and then create new typed DataRow instances (there should be factory methods for you) which can then be put into a typed DataTable, which AsDataView can be called on.

这篇关于将 LINQ 查询绑定到 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆