Question:
My combobox (Me.cbHomeDrive) doesn’t get properly initialized if I use
Me.cbHomeDrive.SelectedText = "E:"
On Form_Load:
For i As Integer = AscW("C"c) To AscW("Z"c) Step 1
Me.cbHomeDrive.Items.Add(New ComboBoxItem(ChrW(i) + ":"))
Next
Me.cbHomeDrive.SelectedIndex = 26 - 3
Me.cbHomeDrive.Enabled = False
With class ComboBoxItem being:
Public Class ComboBoxItem
Public Text As String
Public ID As String
Public Sub New(ByVal strText As String)
Text = strText
ID = strText
End Sub
Public Sub New(ByVal strText As String, ByVal strID As String)
Text = strText
ID = strID
End Sub
Public Overrides Function ToString() As String
Return Text
End Function
End Class
Now If I do
Me.cbHomeDrive.SelectedText = "E:"
right after
Me.cbHomeDrive.Enabled = False
Then nothing happens, and the combobox shows as Z:.
If instead of
Me.cbHomeDrive.SelectedText = "E:"
I use
SetComboBoxToTextIndex(Me.cbHomeDrive, "E:")
with
' WTF '
' http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedtext.aspx '
Sub SetComboBoxToTextIndex(ByVal cbThisComboBox As ComboBox, ByVal strItemText As String)
For i As Integer = 0 To cbThisComboBox.Items.Count - 1 Step 1
If StringComparer.OrdinalIgnoreCase.Equals(cbThisComboBox.Items(i).ToString(), strItemText) Then
cbThisComboBox.SelectedIndex = i
Exit For
End If
Next
End Sub
Then it sets the correct selected item (E:).
Why does it not work with Me.cbHomeDrive.SelectedText = “E:”?
I think you’re misunderstanding what the
SelectedTextproperty is, refer to the MSDN documentation.The
SelectedTextproperty is not the item from the list of items, it’s the portion of an editable combobox that is selected, as if you were doing a copy/paste type of selection.Your
SetComboBoxToTextIndexmethod is the proper way to find and select an item in the list. Aternatively, if your ComboBoxItem properly implementsEquals, you can find the appropriate instance and set theSelectedItemproperty.