如何将查询与连接绑定到DataGridView? [英] How to bind a query with a join to a DataGridView?

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

问题描述

现在,我已经从实体模型的对象上下文创建了一个新的对象数据源。然后我创建了一个BindingSource和一个DataGridView设置到此BindingSource。

Right now, I have created a new Object data source based off from an Object Context from the entity model. I then created a BindingSource and a DataGridView set to this BindingSource.

我可以添加绑定到TraceLine表中的数据的列。当我设置DataSource时,我看到这些列中的值。但是,我似乎无法从连接的表中获取数据。如何将DataGridView绑定到具有连接的查询?

I can add columns which are bound to the data from the TraceLine table. When I set the DataSource, I see values in those columns. However, I can’t seem to get the data from the joined table. How do I bind a DataGridView to a query that has a join?

using (var entities = new MyEntities())
{
    var lines = from t in entities.Lines
                join m in entities.Methods on t.MethodHash equals m.MethodHash
                where t.UserSessionProcessId == m_SessionId
                select new
                {
                    m.Name,  // doesn't get displayed in DataGridView, but I want it to
                    t.Sequence,
                    t.InclusiveDuration,
                    t.ExclusiveDuration
                };

    dgvBindingSource.DataSource = lines;
}


推荐答案

一个可能的问题是DataGridView可能在设计时将其DataSource设置为其中一种类型,但在运行时将其设置为具有额外成员的匿名类型。如果我记得,如果在生成列之后更改数据源,DataGridView将不会重新生成列。

One possible issue is that the DataGridView may have its DataSource set at design time to one of the types but at runtime you're setting it to an anonymous type that has an extra member. If I recall, DataGridView won't re-generate the columns if you change the data source after columns have been generated.

您可能需要将数据源设置为null ,清除列集合,然后设置数据源。事实上,一个更好的主意是明确创建列,而不是自动生成它们。

You may need to set the data source to null, clear the column collection, then set the data source. In fact a better idea would be to create the columns explicitly instead of auto generating them.

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

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