views:

40

answers:

2

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 verification, handling dynamic updates of the source Dictionary and looking nice are a bonus.

A: 

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.

Maurizio Reginelli
I'm limited to Winforms, sadly. Could you show or link to a simple code example?
mafutrct
Here is an example, but you can find lots of them if you google:http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/
Maurizio Reginelli
+3  A: 

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