Binding Controls Within a Custom Control

I have a custom control that contains multiple text boxes bound to a bindingSource. I want to drop this custom control onto another form and pass the data source to the control being used.

I tried to make the user control bindingSource public and set 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 custom control. I have a textbox named textboxFirstName and a binding source called bindingSource

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

Also, using the constructor, I set textboxFirstName.DataBindings.Text to "bindingSource - FirstName" by selecting it from the Person property list.

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

[Update] I can get the binding to work 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'm wondering why setting the binding source alone isn't enough.

Note that at design time I have set up a custom bindingSource DataSource control for humans. This allowed me to select the DataBindings.Text textbox from the list.

+3


source to share


1 answer


You have to use 2 lines first and set the anchor from the designer. The problems are that your dataSource is a collection and you are trying to bind to a textbox. This method only works for controls that contain a collection (datagridview, listbox, etc.). But in your case, in order to bind a textbox to a specific property, the dataSource needs 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, you need to create one text block for each object in the collection, or change the type of the control.

0


source







All Articles