Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!

I'd like to use the same BindingSource to multiple controls. How can I do this?

C#
private void MyBinding()
{
            DataSet ds = new DataSet();
            ds.Tables.Add("MyTable");
            ds.Tables["MyTable"].Columns.Add("MyColumn", typeof(string));
            
            BindingSource bs = new BindingSource();

            bs.DataSource = ds;
            bs.DataMember = "MyTable";

            UserControl1 uc1 = new UserControl1();
            UserControl1 uc2 = new UserControl1();

            this.Controls.Add(uc1);
            this.Controls.Add(uc2);

            uc1.DataBindings.Add(
               new Binding("MyText", bs, "MyColumn", true));

            uc2.DataBindings.Add(
               new Binding("MyText", bs, "MyColumn", true));

            string s1, s2;

            bs.AddNew();

            uc1.MyText = "abc";
            bs.EndEdit();
            
            s1 = ((DataRow)((DataRowView)bs.Current).Row)["MyColumn"].ToString();

            uc2.MyText = "def";
            bs.EndEdit();

            s2 = ((DataRow)((DataRowView)bs.Current).Row)["MyColumn"].ToString();
        
            //result: s1 = "" It should be "abc"
            //        s2 = "def" It's ok.
}

The UserControl1 code:

string myText;
public string MyText
{
    get { return myText; }
    set { myText = value; }
}


If I replace the UserControl to TextBox:
C#
TextBox uc1 = new TextBox();
TextBox uc2 = new TextBox();

and the property MyText to Text, it works fine:
C#
uc1.DataBindings.Add(new Binding("Text", bs, "MyColumn", true));
uc2.DataBindings.Add(new Binding("Text", bs, "MyColumn", true));

Why not do the same, when I use the UserControl1?

Thank You!
Posted
Updated 30-Apr-13 19:48pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900