C# – Simple Windows Forms data binding

cdata-bindingwinforms

Let's say I have a String property in my form (and the form does not implement INotifyPropertyChanged). I've also created a BindingSource and set its DataSource to the form. Then I bind a textbox to the String property on my form (indirectly, using the BindingSource).

Question 1: When I change the value in the textbox at runtime, why don't I hit a breakpoint in the setter of the String property? I thought that binding the control to the String property would allow updates in this direction (GUI -> member data) to occur automatically

Question 2: How can I trigger updates in the other direction (member data -> GUI) to occur when something other than the GUI changes the String property? I don't want to implement the INotifyPropertyChanged interface and add NotifyPropertyChanged to the setter. I thought that by using the BindingSource's ResetBindings I could at least trigger this manually

public partial class Form1 : Form
{
    private String m_blah;
    public String Blah
    { 
        get
        {
            return m_blah;
        }
        set
        {
            m_blah = value;
        }
    }

    public Form1()
    {
        InitializeComponent();
        textBox1.DataBindings.Add(new Binding("Text", bindingSource1, "Blah",true,DataSourceUpdateMode.OnValidation));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Blah = "Clicked!";
        this.bindingSource1.ResetBindings(false); //expecting the GUI to update and say "Clicked!"
    }
}

Best Answer

this.bindingSource1.DataSource = this;

I think you forget to assign data source.

Related Topic