Why isn't this Linq query on Dictionary<TKey, TValue> working as DataSource

断了今生、忘了曾经 提交于 2019-12-10 10:35:38

问题


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.


回答1:


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:

  • IList
  • IListSource (in which case the IListSource.GetList method is used together with the DataMember property to provide data to the control)
  • IBindingList (which propagates changes in the list to the control for UI updates)
  • IBindingListView (like BindingSource)

This is according to the MSDN documentation.




回答2:


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

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