How to bind a query with a join to a DataGridView?

泪湿孤枕 提交于 2019-12-23 01:24:16

问题


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.

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;
}

回答1:


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.

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.



来源:https://stackoverflow.com/questions/3090552/how-to-bind-a-query-with-a-join-to-a-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!