简体   繁体   中英

binding controls inside a user control

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM