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

McBainUK picture McBainUK · Jun 26, 2009 · Viewed 15.4k times · Source

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?

Answer

user110714 picture user110714 · Jun 27, 2009

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... :)