Reputation: 503
If I put:
variableName = namecombobox.selectedItem
or
Dim variablename as type = namecombobox.SelectedIndex
Visual Studio gives me the error
Option Strict disallows conversions from object to string.
I can fix this by putting:
variableName = convert.ToString(namecombobox.SelectedItem)
Are all values contained in a combobox automatically treated as a non-string even when they are string values (in this case "Male" & "Female") and what is the correct way of assigning the value selected in a combobox to a variable?
Upvotes: 3
Views: 12353
Reputation: 446
If you are using this, assuming you select 'Selection1' on the combo box:
Dim x As Boolean
Dim MyVariable As String = ""
MyVariable = ComboBox1.SelectedItem.ToString()
If MyVariable = "Selection1" Then
x = True
Else
x = False
Pretend the above code is YOUR code... This is CORRECT for selecting strings from a ComboBox. Insert a breakpoint on the IF statement checking "MyVariable"- you will see the variable content if you hover your mouse over the variable name. It is a quick way to view the contents of your variable. If hovering above the variable shows an empty string ("") or simply Nothing, then it hasn't picked up any selected item.
In my code above, if I clicked an item containing the words "Selection1", the 'MyVariable' would contain a String of "Selection1" and the boolean variable 'x' would also read as TRUE.
If you're getting reading errors by comparing the variable you have issues elsewhere in your code.
Upvotes: 0
Reputation: 941495
This is normal, the ComboBox.Items property is a collection of System.Object. You should use the item's ToString() method, just like ComboBox does to generate the visible text.
Dim variableName As String = namecombobox.SelectedItem.ToString()
Or use CStr(), the VB.NET way.
Upvotes: 2