【问题标题】:What is the easiest way to display an editable Dictionary?显示可编辑字典的最简单方法是什么?
【发布时间】:2011-02-17 10:36:06
【问题描述】:

我有一个Dictionary<string, string>,希望用户查看和编辑内容,可能会添加新条目。我该怎么做?

输入验证、处理源字典的动态更新以及看起来不错。

【问题讨论】:

    标签: c# winforms dictionary


    【解决方案1】:

    最简单的解决方案是与 DataTable 相互转换并将 GridView 绑定到该数据表。

    DataTables 支持您想要的所有数据绑定支持,并允许您添加和删除行。

    用户完成后,您可以再次将数据表的内容复制到字典中。

    天真和肮脏,但它可以完成工作。

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("foo", "bar");
    
    //translate and bind
    DataTable dt = new DataTable();
    dt.Columns.Add("Key", typeof(string));
    dt.Columns.Add("Value", typeof(string));
    dict
        .ToList()
        .ForEach(kvp => dt.Rows.Add(new object [] {kvp.Key,kvp.Value}));
    
    //allows you to add uniqueness constraint to the key column :-)
    dt.Constraints.Add("keyconstraint", dt.Columns[0], true);
    
    myDataGridView.DataSource = dt;
    

    然后翻译回字典:

    Dictionary<string, string> dict = new Dictionary<string, string>();
    DataTable dt = (DataTable)myDataGridView.DataSource;
    dt.AsEnumerable()
        .ToList()
        .ForEach(row => dict.Add(row[0] as string, row[1] as string));
    

    【讨论】:

      【解决方案2】:

      显示数据结构(如字典)的方法有很多种,这一切都取决于所使用的技术和您想要提供给您的 UI 的布局。
      我认为网格是最简单的,但您也可以尝试其他控件。
      如果您想增强用户体验并制作良好的用户界面,我建议您学习 WPF:通过该技术,您可以为数据结构提供布局并轻松进行更改,直到获得最佳结果。

      【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 2011-01-23
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多