public partial class Form1 : Form
{
MyClass myClass = new MyClass("one", "two");
public Form1()
{
InitializeComponent();
textBox1.DataBindings.Add("Text", myClass, "Text1", false, DataSourceUpdateMode.Never);
textBox2.DataBindings.Add("Text", myClass, "Text2", false, DataSourceUpdateMode.Never);
}
private void saveButton_Click(object sender, EventArgs e)
{
myClass.Text1 = textBox1.Text;
myClass.Text2 = textBox2.Text;
//textBox1.DataBindings["Text"].WriteValue();
//textBox2.DataBindings["Text"].WriteValue();
}
}
public class MyClass : INotifyPropertyChanged
{
private string _Text1;
private string _Text2;
public event PropertyChangedEventHandler PropertyChanged;
public string Text1
{
get { return _Text1; }
set { _Text1 = value; OnPropertyChanged(new PropertyChangedEventArgs("Text1")); }
}
public string Text2
{
get { return _Text2; }
set { _Text2 = value; OnPropertyChanged(new PropertyChangedEventArgs("Text2")); }
}
public MyClass(string text1, string text2)
{
Text1 = text1;
Text2 = text2;
}
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null) PropertyChanged(this, e);
}
}
I think is pretty clear what I'm trying to achieve. I want my form to save the changes made in my two TextBox
es to myClass
. But whenever I press the save button after editing both text boxes, and saveButton_Click
is invoked, the second textBox2
's Text
goes back to the original text ("two"). I tried using Binding
's WriteValue
function but the same thing happens. Using .net 4.0.
Edit Thanks for your answers, but I don't need workarounds. I can find them myself. I just need to understand a little bit better how binding works. I would like to understand why is this happening?