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

故事扮演 提交于 2019-12-06 04:56:17

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:

This is according to the MSDN documentation.

You may need to call DataBind after setting the source. Try:

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