问题
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