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 calls MoveNext somewhere (as happens within a foreach loop, for example).
It seems the DataSource property does not enumerate its contents in this way. It's completely expecting an implementation of IList (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 the DataSource property does is check the object's type to see whether it implements any of the supported interfaces. So I don't think the DataSource property is designed to deal with this type of object (a lazily evaluated query) at all.
Now, that ToList call populates a List<T> with the results of your query; this does implement IList and can therefore be used as the DataSource.
My understanding is that the reason DataSource is typed merely as object is 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.
You may need to call DataBind after setting the source. Try:
dgridSourceFiles.DataSource = sources
dgridSourceFiles.DataBind()
来源:https://stackoverflow.com/questions/4502827/why-isnt-this-linq-query-on-dictionarytkey-tvalue-working-as-datasource