问题描述
是否可以自动将Dictionary绑定到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();
这会将myObject中的属性绑定到gridview,但是我也想获取键.如果不可能,是否有替代方法,例如使用中继器?谢谢.
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.
推荐答案
您可以使用:
var data = MyDictionary.Select(x => new List<object>{x.Key, x.Value});
这将为您提供 IEnumerable< List< object>>
,其中 IEnumerable
代表行",并且在每一行中, List< object>
代表列".
This will give you an IEnumerable<List<object>>
, where the IEnumerable
represents the "rows" and within each row the List<object>
represents the "columns."
如果 myObject
是集合类型,则此方法会稍有不同.我无法从您的代码中确定,但事实并非如此.
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.
这篇关于如何将字典绑定到gridview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!