How to bind a dictionary to a gridview?

◇◆丶佛笑我妖孽 提交于 2021-01-27 18:18:17

问题


Is it possible to automatically bind a Dictionary to a Gridview? The closest I've got is:

Dictionary<string, myObject> MyDictionary = new Dictionary<string, myObject>();
// Populate MyDictionary here.
Grid1.DataSource = MyDictionary.Values;
Grid1.DataBind();

This binds the properties in myObject to the gridview, but I'd like to get the key as well. If it's not possible, is there an alternative, e.g. use a repeater? Thanks.


回答1:


You can use:

var data = MyDictionary.Select(x => new List<object>{x.Key, x.Value});

This will give you an IEnumerable<List<object>>, where the IEnumerable represents the "rows" and within each row the List<object> represents the "columns."

This would be slightly different if myObject is a collection type. I can't be certain from your code, but it doesn't look like this is the case.




回答2:


You need to bind the columns to "Key" and "Value", I believe.




回答3:


I think the best way is to convert into List>

List<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>();
list.AddRange(dictionary);
Grid1.DataSource = list;

this also allows to do easy sorting:

list.Sort(delegate...);

then pass it as the DataSource.




回答4:


I have no idea how well dictionary works as a itemsSource. I guess not at all unless Dictionary implements IEnumerable or ICollection.

You could however create your own object that holds a Key string property and your Object and have a collection of such items. However that will lack many things Dictionary has ( like unique Keys and such ).

Perhaps Dictionary has a ToList() method

Does it give you an error when putting the Dictionary as a source. If not perhaps you have to set the DisplayMemberPath on the columns as Value and Key.




回答5:


Per the MSDN, the DataSource must be an object that implements one of the following interfaces:

  • The IList interface, including one-dimensional arrays.
  • The IListSource interface, such as the DataTable and DataSet classes.
  • The IBindingList interface, such as the BindingList class.
  • The IBindingListView interface, such as the BindingSource class.

Dictionary does not implement any of those interfaces. The closest you can get would be to use List<KeyValuePair<string, myObject>>.



来源:https://stackoverflow.com/questions/4627143/how-to-bind-a-dictionary-to-a-gridview

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