Search code examples
c#.netwinformsdata-bindingcombobox

ComboBox or ListBox as index of Form - Bind other controls to SelectedItem


This is actually a very simple and basic question, and my apologies if this is a repeat question (surely it must be), but I can't find a straightforward answer anywhere and am finally throwing in the towel.

I have created a Windows Forms app in Visual Studio '17, created a data source based upon an SQL server table, and added a bound combobox. So far so good. Using the drag and drop feature from the DataSource/DataSet panel, I populate a few fields in text boxes and bind to data. Using the data binding navigator automatically added, I can scroll through the table and the controls all update, so I know they are all properly bound.

Now, all I want to accomplish is to have the controls update when the combobox selected value changes. But they do not. From what I've read, I'm guessing that somehow the combobox needs to alert that the datasource current record needs updating? If so, how do I get it to update to the key value from the combobox? Or maybe this is completely wrong? My hope was that VS would do its magic for bound controls so that I don't have to handle each combo change event, query the database, and then update each control.

I thought this would be a simple task; given that it's so very basic, surely there would be straight forward explanations, but either problems discussed are more complicated or else a labyrinth of data binding procs and objects are discussed. This is sort of a side venture from my usual .net and SQL coding, so I am hoping a straight forward event handler or two is all that's needed.


Solution

  • When you want to setup a list control like ComboBox or ListBox to act as an index for data:

    • Set its DataSource property to the same DataSource to which other controls are bound.
    • Set its DisplayMember to show in combo box, but you don't need to set ValueMember.
    • Don't touch (DataBindings). You don't need to set up data-binding.

    Example

    Assuming you have a productsBindingSource, these are settings for bound controls:

    • idTextBox → Data Bindings: Text property bound to Id property of productsBindingSource
    • nameTextBox → Data Bindings: Name property bound to Name property of productsBindingSource
    • priceTextBox → Data Bindings: Price property bound to Price property of productsBindingSource

    Then to have a ComboBox to act as index, these are the settings for ComboBox:

    • DataSource property set to productsBindingSource
    • DisplayMember property set to Name
    • Don't touch (DataBindings). You don't need to set up data-binding.

    Then as a result, when you select an item from ComboBox, bound controls will show selected item and binding navigator will move as well:

    enter image description here