Question

I have a populated combobox that I would like to bind to an Integer.
The wanted behaviour is that when the datasource changes to a new object, the combobox selected value changes accordingly to the Integer binded to it.

The problem is that the default binding(I simply dragged and dropped my Integer from the datasource pannel over the combobox) binds the text property of the combobox, not the SelectedIndex.

Right now I kinda make it work this way:

BindingSourceName.DataSource = Object
cmbType.SelectedIndex = Object.Type  

But I have to manually manage it also while saving the binded object upon User modifications.
Is there a proper way to change the default bindig bahaviour to make it automatically bind the Integer to the SelectedIndex of my combobox?

Was it helpful?

Solution

The closest I can get to what you want is if I use a ValueMember for the index. For example:

I fill my Combobox with a couple of Items like this:

Public Class NameValue 
Property Name as String
Property Type as Integer
Public Sub New(ByVal pName as String, ByVal pVal as Integer)
Name = pName
Type = pValue
End Sub
End Class

Dim cmbList As New List(Of NameValue)
cmbList.Add(New NameValue("Name",1)
cmbList.Add(New NameValue("Name2",2)
cmbList.Add(New NameValue("Name3",3)

cmbType.Items = cmbList
cmbType.ValueMember = "Value"
cmbType.DisplayMember = "Type"

Now the first stage is complete. The Combobox contains three items with a name and a value bound together. Next step is to setup what you are asking for: Bind the ComboboxValue to the Object class.

cmbType.DataBindings.Add(New Binding("SelectedValue", BindingSourceName, "Type", False, DataSourceUpdateMode.OnPropertyChanged))

As soon as the BindingSource "BindingSourceName.DataSource" changes, the combobox should be updated. And if you change the combobox, the Object.Type will change to the selected Value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top