3
votes

I have a user control that contains several text boxes bound to a bindingSource. I want to drop that user control onto another form and pass the datasource to the control to use.

I have tried making the user control's bindingSource public and setting it to the same bindingSource on the form,

    List<Person> data = MyGetData(); // returns a list of people
    this.formControl.bindingSource.DataSource = data;   // where formControl is my user control containing bound text boxes.

inside my user control I have a textbox called textboxFirstName, and a bindingsource called bindingSource

Using the designer, I set bindingSource.DataSource to be Person where Person is one of my domain classes.

Also using the designer I set textboxFirstName.DataBindings.Text to "bindingSource - FirstName" by picking it from the list of Person properties.

There is no error message, but the text box is not displaying the data.

[Update] I can get the binding working if I create the following procedure and call it.

    public void SetBinding(BindingSource bs)
    {
        this.bindingSource = bs;
        this.firstNameTextBox.DataBindings.Clear();
        this.firstNameTextBox.DataBindings.Add(new Binding("Text", bs, "firstName"));
    }

However I am wondering why setting the binding source alone is not enough.

Note at design time I had set the user control's bindingSource DataSource to People. This enabled me to pick the text box's DataBindings.Text property from a list.

1
What error do you get when you pass it the same bindingsource?Kat
Hi @sparkysword I updated the question to show that there is no error message, the data just does not bind.Kirsten
@LarsTech I updated the question to show that I set the DataBindings.Text at design timeKirsten
Kirsten, I don't thing setting the databinding's text property to a particular string is the same thing as doing the .add() function. in that one you actually point to a binding source (bs) and not just some random (to C#) set of characters.Kat
@sparkysword I updated the question to show that the text I used was picked at design time. It is not some random set of charactersKirsten

1 Answers

0
votes

You first 2 lines and setting the binding from the designer should work. The issues is that your dataSource is a collection and you are trying to bind it to a textbox. This method only works for controls that hold a collection (datagridview, listbox, etc.). But in your case, in order to bind a textBox to a certain property you need the dataSource to be one Person object that has that property.

try this line:

this.formControl.bindingSource.DataSource = data.First();

and see if your text is displayed. If you want to display the entire collection than you need to create one textBox for every object in the collection or change the control type.