How do I Change comboBox.Text inside a comboBox.SelectedIndexChanged event?

16,327

Solution 1

You should reset the SelectedIndex property to -1 when setting the Text property.

Solution 2

Move your change code outside of combobox event:

if(some condition)
{
    BeginInvoke(new Action(() => comboBox.Text = "new string"));
}

Solution 3

Perhaps it would help if you could explain exactly what you're trying to do. I find that the SelectionChangeCommitted event is considerably more useful for purposes like what you describe than SelectedIndexChanged. Among other things, it's possible to change the selected index again from SelectionChangeCommitted (e.g. if the user's selection is invalid). Also, changing the index from code fires SelectedIndexChanged again, whereas SelectionChangeCommitted is only fired in response to user actions.

Solution 4

In short, .NET is trying to prevent an endless loop that could occur. When a change to the Text property occurs, .NET will try to match that new value to the current items and change the index for you, thereby firing the SelectedIndexChanged event again.

People coming here looking for a VB implementation of Delegates can refer to the code below

'Declares a delegate sub that takes no parameters
Delegate Sub ComboDelegate()

'Loads form and controls
Private Sub LoadForm(sender As System.Object, e As System.EventArgs) _
    Handles MyBase.Load
    ComboBox1.Items.Add("This is okay")
    ComboBox1.Items.Add("This is NOT okay")
    ResetComboBox()
End Sub

'Handles Selected Index Changed Event for combo Box
Private Sub ComboBoxSelectionChanged(sender As System.Object, e As System.EventArgs) _
    Handles ComboBox1.SelectedIndexChanged
    'if option 2 selected, reset control back to original
    If ComboBox1.SelectedIndex = 1 Then
        BeginInvoke(New ComboDelegate(AddressOf ResetComboBox))
    End If

End Sub

'Exits out of ComboBox selection and displays prompt text 
Private Sub ResetComboBox()
    With ComboBox1
        .SelectedIndex = -1
        .Text = "Select an option"
        .Focus()
    End With
End Sub

Further Reading: See this post (mine) on changing Combobox Text in the SelectedIndexChanged Event which goes into a little more detail as to why you need to use a delegate as a workaround to change the ComboBox Text.

Solution 5

//100% worked

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
      BeginInvoke(new Action(() => ComboBox1.Text = "Cool!");
}
Share:
16,327
McBainUK
Author by

McBainUK

Updated on June 18, 2022

Comments

  • McBainUK
    McBainUK almost 2 years

    Code example:

    private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(some condition)
        {
            comboBox.Text = "new string"
        }
    }
    

    My problem is that the comboBox text always shows the selected index's string value and not the new string. Is the a way round this?