I want to bind a textBox’s data to a Dictionary<string,string> entry. I am trying to achieve this through data binding, so the content get updated after the user edited the textBox.
This is a demo code of what I have done:
A classA that has a Name and List dictionary:
class ClassA
{
public string Name { get; set; }
public Dictionary<string, string> List { get; set; }
public ClassA()
{
this.Name = "Hello";
this.List = new Dictionary<string, string>
{
{"Item 1", "Content 1"},
{"Item 2", "Content 2"}
};
}
}
In the Form, I bind textBox1 to Name and textBox2 to List["Item 1"]:
ClassA temp = new ClassA();
public Form1()
{
InitializeComponent();
textBox1.DataBindings.Add("Text", temp, "Name");
textBox2.DataBindings.Add("Text", temp.List["Item 1"], "");
label1.DataBindings.Add("Text", temp, "Name");
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
label1.Text = temp.List["Item 1"];
}
If I change textBox1 text, label1 content (Name) will successfully updated.
But if I change textBox2 text, label1 content will show the original List["Item 1"] value.
How can I bind textBox2 to List["Item 1"] correctly?
Use explicit binding and consume its events to achieve your goal
Parse event will occur when the value of a data-bound control changes.
Format event will occur when the property of a control is bound to a data value.