Apparently, updating any value in the data source will update all the bindings. This explains the behavior (setting myClass.Text1 causes myClass.Text1 be updated with the current value myClass.Text2 ). Unfortunately, a few posts I could find simply said, "how does it work."
One way to handle this is to create a BindingSource , set BindingSource.DataSource = myClass , and then bind your text fields to BindingSource .
BindingSource raises ListChanged events if the main data source is a list and items are added, deleted, etc., or if the properties of the DataSource changed. You can suppress these events by setting BindingSource.RaiseListChangedEvents to false , which allows you to set multiple properties on myClass without updating the data binding of the associated controls.
public partial class Form1 : Form { MyClass myClass = new MyClass("one", "two"); BindingSource bindingSource = new BindingSource(); public Form1() { InitializeComponent(); bindingSource.DataSource = myClass; textBox1.DataBindings.Add("Text", bindingSource, "Text1", true, DataSourceUpdateMode.Never); textBox2.DataBindings.Add("Text", bindingSource, "Text2", true, DataSourceUpdateMode.Never); } private void button1_Click(object sender, EventArgs e) { bindingSource.RaiseListChangedEvents = false; myClass.Text1 = textBox1.Text; myClass.Text2 = textBox2.Text; bindingSource.RaiseListChangedEvents = true; } }
NTN
source share