Is there a standard control that lets a user edit the key-value pairs of a String to String Dictionary?
If not, how would you implement one? I've got a few ideas but none of them seems great.
Is there a standard control that lets a user edit the key-value pairs of a String to String Dictionary?
If not, how would you implement one? I've got a few ideas but none of them seems great.
No, there isn't one built in. For implementing one; how about a 2-column DataGridView
, implementing IDataErrorInfo
such that duplicated keys result in a red error blob:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
class Pair : IDataErrorInfo
{
internal IList<Pair> Parent { get; set; }
public string Key { get; set; }
public string Value { get; set; }
string IDataErrorInfo.Error
{
get { return ""; }
}
string IDataErrorInfo.this[string columnName]
{
get
{
if(columnName == "Key" && Parent != null && Parent.Any(
x=> x.Key == this.Key && !ReferenceEquals(x,this)))
{
return "duplicate key";
}
return "";
}
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
BindingList<Pair> pairs = new BindingList<Pair>();
// todo: fill from StringDictionary
pairs.AddingNew += (s,a) =>
{
a.NewObject = new Pair { Parent = pairs };
};
Application.Run(new Form {
Controls = {new DataGridView {
Dock = DockStyle.Fill,
DataSource = pairs
}}
});
}
}
Just make a list and databind them to a grid. Quick & easy.
EDIT: here's an example, assumed you have a form with a GridView on it.
Dictionary<string, string> d;
protected void Page_Load(object sender, EventArgs e)
{
d = new Dictionary<string, string>();
d.Add("key 1", 1);
d.Add("key 2", 2);
d.Add("key 3", 3);
d.Add("key 4", 4);
d.Add("key 5", 5);
GridView1.DataSource = d;
GridView1.DataBind();
}
For error handling etc, check Marc's answer. You might also want to do some more research on DataBinding.