Search code examples
c#comboboxselectedindexchanged

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


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?


Solution

  • This code should work...

    public Form1()
    {
        InitializeComponent();
    
        comboBox1.Items.AddRange(new String[] { "Item1", "Item2", "Item3" });
    }
    
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        String text = "You selected: " + comboBox1.Text;
    
        BeginInvoke(new Action(() => comboBox1.Text = text));
    }
    

    Hope it helps... :)