开发者

How to bind a dictionary to a gridview?

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();
开发者_Python百科

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.


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


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.


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.


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.


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>>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜