How do I Change comboBox.Text inside a comboBox.Se

2019-05-11 13:41发布

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?

9条回答
smile是对你的礼貌
2楼-- · 2019-05-11 14:21

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.

查看更多
Fickle 薄情
3楼-- · 2019-05-11 14:22

you should use:

BeginInvoke(new Action((text) => comboBox.Text = text), "new text to set");

查看更多
再贱就再见
4楼-- · 2019-05-11 14:23

//100% worked

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
      BeginInvoke(new Action(() => ComboBox1.Text = "Cool!");
}
查看更多
Fickle 薄情
5楼-- · 2019-05-11 14:25

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

查看更多
ゆ 、 Hurt°
6楼-- · 2019-05-11 14:31

I searching for solution for same issue. But solve it by handling Format event:

cbWatchPath.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.cbWatchPath_Format);

private void cbWatchPath_Format(object sender, ListControlConvertEventArgs e)
    {
        e.Value = "Your text here";
    }
查看更多
劳资没心,怎么记你
7楼-- · 2019-05-11 14:32

Move your change code outside of combobox event:

if(some condition)
{
    BeginInvoke(new Action(() => comboBox.Text = "new string"));
}
查看更多
登录 后发表回答