Why does this Linq query in the <TKey, TValue> dictionary work like a DataSource
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 the request in memory and has 2 entries inside. However, records will not be displayed in the datagrid view.
So why is this not working? sentences 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 data source is displayed.
Your LINQ query is lazily evaluated and implements only the IEnumerable<T> interface (as far as I know), which means that its results are not set until the enumerator calls MoveNext somewhere (as it happens in the foreach for example).
The DataSource property does not seem to list its contents in this way. It fully expects the implementation of IList (or one of several other interfaces - see below) so that it can access elements by index. This is used by the internal control for sorting, filtering, etc. With this in mind, it is likely that all the settings for the DataSource property are an object type check to verify that it implements any of the supported interfaces. Therefore, I do not think that the DataSource property is designed to work with this type of object (lazily evaluated query) in general.
Now this ToList call populates the List<T> results of your query; it implements IList and therefore can be used as a DataSource .
I understand that the reason DataSource is entered simply as object is that it expects any of the following interfaces:
IListIListSource(in this case, theIListSource.GetListmethodIListSource.GetListused together with theDataMemberproperty to provide data to the control)IBindingList(which propagates the changes in the list to the control for user interface updates)IBindingListView(e.g.BindingSource)
This is consistent with the MSDN documentation .
You may need to call DataBind after setting the source. Try:
dgridSourceFiles.DataSource = sources dgridSourceFiles.DataBind()