What I'm trying to do :
- Add a form to a new project
- Add a comboBox to the form with DropDownStyle = DropDown
- In form load :
ComboBox1.Items.Add("01 - USA")
ComboBox1.Items.Add("31 - Holland")
ComboBox1.Items.Add("33 - France")
ComboBox1.Items.Add("41 - Switzerland")
The desired behaviour is that when a user selects a list item only the
number is displayed in the textbox part of the comboBox. So if "01 -
USA" is selected only "01" should be displayed.
Roughly translating the way this would be done in VB6 I tried the
following code :
Private Sub ComboBox1_SelectionChangeCommitted( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles ComboBox1.SelectionChangeCommitted
Dim listItemText As String
If ComboBox1.SelectedIndex >= 0 Then
'Calculate and store the value we want to display
listItemText = ComboBox1.SelectedItem.ToString
If listItemText.Length >= 2 Then
listItemText = listItemText.Substring(0, 2)
End If
'Cancel the selection
ComboBox1.SelectedIndex = -1
'Update the textbox part
ComboBox1.Text = listItemText
End If
End Sub
However this doesn't work. I've also tried experimenting with the
SelectedValueChanged, SelectedIndexChanged and TextChanged events,
with no better results. It seems that changing the selectedIndex in
any of these routines always cancels out changes made via the text
property, whatever the order the operations are carried out in.
I've finally resorted to using a timer to update ComboBox1.Text after
all these events have finished firing, but it's a very shoddy
solution.
Surely there must be a way to do this properly?