显示可编辑词典的最简单方法是什么? [英] What is the easiest way to display an editable Dictionary?

查看:58
本文介绍了显示可编辑词典的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dictionary<string, string>,想让用户查看和编辑内容,可能会添加新条目.我该怎么办?

I've got a Dictionary<string, string> and would like to have the user to see and edit the content, possibly adding new entries. How should I do that?

输入验证,处理源Dictionary的动态更新以及看起来不错都是一个奖励.

Input verification, handling dynamic updates of the source Dictionary and looking nice are a bonus.

推荐答案

绝对最简单的解决方案是与DataTable进行相互转换,然后将GridView绑定到该数据表.

The absolutely simplest solution would be to translate to and from a DataTable and bind a GridView to that.

DataTable支持所需的所有数据绑定支持,并允许您添加和删除行.

The DataTables support all the databinding support you want and allows you to add and remove rows.

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

Once the user is done, you could copy the contents of the datatable into your dictionary again.

天真又肮脏,但是可以完成工作.

Naive and dirty, but it would get the job done.

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));

这篇关于显示可编辑词典的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆