【问题标题】:How to bind a dictionary to a gridview?如何将字典绑定到gridview?
【发布时间】:2011-06-05 08:33:57
【问题描述】:

是否可以自动将字典绑定到 Gridview?我得到的最接近的是:

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

这会将 myObject 中的属性绑定到 gridview,但我也想获取密钥。如果不可能,是否有替代方案,例如使用中继器?谢谢。

【问题讨论】:

  • 您是在谈论 DataGridView(我不熟悉)而不是像 ListView 那样使用 GridView 吗?如果是这样,我想我的答案不适用。
  • 目前我只是将两个 asp.net gridviews 并排放置,一个绑定到 MyDictionary.Keys,另一个绑定到 MyDictionary.Values。

标签: c# asp.net data-binding gridview dictionary


【解决方案1】:

我觉得最好的办法是转成List>

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

这也允许进行简单的排序:

list.Sort(delegate...);

然后将其作为数据源传递。

【讨论】:

    【解决方案2】:

    根据MSDN,DataSource 必须是实现以下接口之一的对象:

    • IList 接口,包括一维数组。
    • IListSource 接口,例如 DataTable 和 DataSet 类。
    • IBindingList 接口,例如 BindingList 类。
    • IBindingListView 接口,例如 BindingSource 类。

    字典没有实现任何这些接口。您可以获得的最接近的方法是使用List&lt;KeyValuePair&lt;string, myObject&gt;&gt;

    【讨论】:

    • 这是针对 WinForms DataGridView 控件的,不是针对 ASP.NET GridView 控件的。
    【解决方案3】:

    我不知道字典作为 itemsSource 的效果如何。我想根本不会,除非 Dictionary 实现 IEnumerable 或 ICollection。

    但是,您可以创建自己的对象,该对象包含 Key 字符串属性和您的 Object,并拥有此类项目的集合。但是,这将缺少 Dictionary 所拥有的许多东西(例如唯一键等)。

    也许 Dictionary 有一个 ToList() 方法

    将字典作为来源时是否会给您一个错误。如果不是,您可能必须将列上的 DisplayMemberPath 设置为 Value 和 Key。

    【讨论】:

    • 事实上,字典确实实现了IEnumerableICollection&lt;KeyValuePair&lt;TKey, TValue&gt;IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;msdn.microsoft.com/en-us/library/s4ys34ea.aspx
    • 那我不明白为什么它不能像任何其他集合一样用作 ListView 的 itemsSource。
    【解决方案4】:

    你可以使用:

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

    这将为您提供IEnumerable&lt;List&lt;object&gt;&gt;,其中IEnumerable 代表“行”,而在每一行中,List&lt;object&gt; 代表“列”。

    如果myObject 是一个集合类型,这会略有不同。从您的代码中我无法确定,但看起来情况并非如此。

    【讨论】:

    • .GetEnumerator() 会做同样的事情吗?
    • @Ing 枚举将是 KeyValuePair&lt;string, myObject&gt; 类型的对象。
    • 谢谢,不幸的是,我们仍在使用 .NET 2.0,所以我认为这不适用于我的情况。 myObject 不是集合类型。
    【解决方案5】:

    您需要将列绑定到“Key”和“Value”,我相信。

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 2011-02-28
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多