What is the easiest way to display an editable Dictionary?
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?
Input verificat开发者_C百科ion, handling dynamic updates of the source Dictionary and looking nice are a bonus.
The absolutely simplest solution would be to translate to and from a DataTable and bind a GridView to that.
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;
And to translate back to dict:
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));
There are many ways to display a data structure like a dictionary and all depends from the technology used and the layout that you want to give to you UI.
I think that a grid is the simplest one, but you can try also other controls.
If you want to enhance the user experience and making a good User Interface, I suggest you to study WPF: with that technology you can give a layout to a data structure and easily make changes until you get the best result.
精彩评论