问题
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