I have the following in VB:
Dim sources = From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}
dgridSourceFiles.DataSource = sources
When I debug, sources shows an in-memory query and has 2 records within. Yet the datagrid view will not show the records.
So why won’t this work? suggestions can be either VB or C#…
Update
When I use:
Dim sources = (From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}).ToList()
…the datasource is displayed.
Your LINQ query is lazily evaluated and implements the
IEnumerable<T>interface only (as far as I know), which means its results are not established until an enumerator callsMoveNextsomewhere (as happens within aforeachloop, for example).It seems the
DataSourceproperty does not enumerate its contents in this way. It’s completely expecting an implementation ofIList(or one of a few other interfaces—see below) so that it can access items by index. This is used internally by the control for sorting, filtering, etc. With this in mind, it’s likely that all setting theDataSourceproperty does is check the object’s type to see whether it implements any of the supported interfaces. So I don’t think theDataSourceproperty is designed to deal with this type of object (a lazily evaluated query) at all.Now, that
ToListcall populates aList<T>with the results of your query; this does implementIListand can therefore be used as theDataSource.My understanding is that the reason
DataSourceis typed merely asobjectis that it expects any of the following interfaces:IListIListSource(in which case theIListSource.GetListmethod is used together with theDataMemberproperty to provide data to the control)IBindingList(which propagates changes in the list to the control for UI updates)IBindingListView(likeBindingSource)This is according to the MSDN documentation.