I need TextBox which will reflect changes in databound string. I tried following code:
public partial class Form1 : Form
{
string m_sFirstName = "Brad";
public string FirstName
{
get { return m_sFirstName; }
set { m_sFirstName = value; }
}
public Form1()
{
InitializeComponent();
textBox1.DataBindings.Add("Text", this, "FirstName");
}
private void buttonRename_Click(object sender, EventArgs e)
{
MessageBox.Show("before: " + FirstName);
FirstName = "John";
MessageBox.Show("after: " + FirstName);
}
}
After launching an application, textBox1 is correctly filled with Brad.
I clicked the Button, it renamed FirstName to “John” (second messagebox confirms it).
But the textBox1 is still filled with Brad, not with John. Why? What will make this work?
The reason why the DataBinding is not reflecting your changes is because you are binding a simple System.String object which have not been designed to throw events when modified.
So you have 2 choices. One is to rebind the value when in the Click event of your button (please avoid!). The other is to make a custom class that will implement INotifyPropertyChanged like this:
INotifyPropertyChanged documentation : MSDN