Search code examples
c#.netwinformsado.netbindingsource

Adding data to DataSource from UI with BindingSource


I have a form (Form1) which contains a grid, bound to a DataSource via a BindingSource.

I then have a button, which once clicked opens another form (Form2) that should let a user enter new data.

I pass the BindingSource from Form1 to Form2, and the goal is that once the user "saves" his input in Form2, it'll be automatically added to Form1.

Is there a way to do this, w/o directly accessing the UI controls?

I.E -

public partial class Form2 : Form
{
    BindingSource bs = new BindingSource();
    public Form2(BindingSource bindingSourceFromForm1)
            {
                InitializeComponent();
                this.bs = bindingSourceFromForm1;
            }    
    private void button1_Click(object sender, EventArgs e)
            {
                DataRow dr = (this.bs.DataSource as DataTable).NewRow();
                dr["Col1"] = this.textBox1.Text;
                dr["Col2"] = this.textBox2.Text;
                this.bs.Add(dr);
            }
}

Is there a way to bind the controls on Form2 (in the example above textBox1/2) to the BindingSource, and then have it automatically add the values in textBox1 & 2?

Something like calling this.bs.Add(), where Add() knows where to take it's values without me explicitly telling it to go to the textboxes, since it's bound to the aforementioned controls?

Thanks!


Solution

  • If you add a BindingSource to the form designer as you would normally do, set the DataSource to the same source so you can bind the textboxes.

    In the specialized constructor the following code adds a new record to the DataSource of form1, assigns the DataSource to the DataSource of the BindingeSource instance of this form and sets the position. Your new Form will enable the user the enter the values in that new object.

    public Form2(BindingSource bindingSourceFromForm1)
        : this()
    {
        bindingSourceFromForm1.AddNew();
        this.bindingSource1.DataSource = bindingSourceFromForm1.DataSource;
        this.bindingSource1.Position = bindingSourceFromForm1.Position;
    }
    

    If your user can cancel the operation you have to compensate for that by calling RemoveCurrent on the bindingSourceFromForm1 but I leave that as excersice as it is not clear if you want/need that.