Search code examples
stringvb.netcomboboxdata-manipulation

Changing Value of Combo Box to another Value in VB


I am trying to change the value of a combo box value "Black Shredded - 7.90" to just show "Black Shredded" when it is selected

    Dim intIndex As Integer
    Dim strString1 As String
    Dim strString2 As String

    strString1 = cboProduct.SelectedItem
    intIndex = strString1.IndexOf(" ")
    strString2 = strString1.Remove(intIndex + 9)

    If cboProduct.SelectedIndex = 0 Then
        cboProduct.Text = strString2
    End If

I went through the values and they show as they should but it isn't changing the combobox value what could I be doing wrong?


Solution

  • If you have just added Strings to the ComboBox in the first place then you need to replace the existing item with the new value. This:

    cboProduct.Text = strString2
    

    should be this:

    cboProduct.Items(cboProduct.SelectedIndex) = strString2
    

    You can just use 0 rather than cboProduct.SelectedIndex, given that you have already confirmed that that is the index at that point.

    Setting the Text property doesn't affect the items at all. If DropDownStyle is set to DropDown then the specified text will be displayed but no item will be selected. If DropDownStyle is set to DropDownList then the item with that text will be selected, if one exists. Either way, no item is added or changed.