栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

绑定到字典的DataGridView

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

绑定到字典的DataGridView

有两个问题

Dictionary
; 第一个是(如您所发现的)它没有实现必要的
IList
/
IListSource
。第二个原因是,没有对项目的保证顺序(实际上,也没有索引器),这使得无法通过索引(而不是键)进行随机访问。

但是…可能有些烟和镜子是可行的。如下所示:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Windows.Forms;static class Program{    [STAThread]    static void Main()    {        Dictionary<string, decimal> prices = new Dictionary<string, decimal>();        prices.Add("foo", 123.45M);        prices.Add("bar", 678.90M);        Application.EnableVisualStyles();        Form form = new Form();        DataGridView dgv = new DataGridView();        dgv.Dock = DockStyle.Fill;        form.Controls.Add(dgv);        var bl = prices.ToBindingList();        dgv.DataSource = bl;        Button btn = new Button();        btn.Dock = DockStyle.Bottom;        btn.Click += delegate        { prices.Add(new Random().Next().ToString(), 0.1M); bl.Reset();        };        form.Controls.Add(btn);        Application.Run(form);    }    public static DictionaryBindingList<TKey, TValue>        ToBindingList<TKey, TValue>(this IDictionary<TKey, TValue> data)    {        return new DictionaryBindingList<TKey, TValue>(data);    }    public sealed class Pair<TKey, TValue>    {        private readonly TKey key;        private readonly IDictionary<TKey, TValue> data;        public Pair(TKey key, IDictionary<TKey, TValue> data)        { this.key = key; this.data = data;        }        public TKey Key { get { return key; } }        public TValue Value        { get {     TValue value;     data.TryGetValue(key, out value);     return value; } set { data[key] = value; }        }    }    public class DictionaryBindingList<TKey, TValue>        : BindingList<Pair<TKey, TValue>>    {        private readonly IDictionary<TKey, TValue> data;        public DictionaryBindingList(IDictionary<TKey, TValue> data)        { this.data = data; Reset();        }        public void Reset()        { bool oldRaise = RaiseListChangedEvents; RaiseListChangedEvents = false; try {     Clear();     foreach (TKey key in data.Keys)     {         Add(new Pair<TKey, TValue>(key, data));     } } finally {     RaiseListChangedEvents = oldRaise;     ResetBindings(); }        }    }}

请注意,自定义扩展方法的使用完全是可选的,并且可以在C#2.0等中通过仅使用

newDictionaryBindingList<string,decimal>(prices)
来删除。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号