sabato 28 aprile 2012

Bind a ComboBox to a generic Dictionary

The SelectedValue property of a ComboBox works only if the combobox is bound to a datasource.
If you manually assign values to combobox and try to set Combobox.SelectedValue, you would find that this command has no effect: and the selected value of combobox does not change.

So if You want to fill a Combobox with a simple fixed list of values, and you don't have, or don't want to get data from a database using a datatable object, You can bind the Combobox DataSource property to a generic Dictionary.

Here is the sample source code:

'Declare and Fill a generic Dictionary

        Dim dictionary As New Dictionary(Of String, Integer)
        dictionary.Add("one", 1)
        dictionary.Add("two", 2)
        dictionary.Add("three", 3)
        dictionary.Add("four", 4)
        dictionary.Add("five", 5)
        dictionary.Add("six", 6)
        dictionary.Add("seven", 7)
        dictionary.Add("eight", 8)

'Initialize DisplayMember and ValueMember of an existing combobox to be filled with dictionary values
         cboCombo.DisplayMember = "Key"
         cboCombo.ValueMember = "Value"

'Bind the combobox to dictionary
         cboCombo.DataSource = New BindingSource(dictionary, Nothing)

'Now I can assign the selected value of combobox with this simple command:
         cboCombo.SelectedValue = 4

'I can also retrive the selected value with:
          value = cboCombo.SelectedValue

6 commenti:

  1. Thanks for this, I just need that

    RispondiElimina
  2. Thanks

    http://dotnet-developers-cafe.blogspot.in/search/label/All

    RispondiElimina
  3. Questo commento è stato eliminato dall'autore.

    RispondiElimina
  4. There's a small error in your code, the values of DisplayMember and ValueMember should be the other way round:

    cboCombo.DisplayMember = "Value"
    cboCombo.ValueMember = "Key"

    RispondiElimina
  5. Thank you so much.. finally got out with combobox's key and value problem. Thank you so much. :)

    RispondiElimina