Code Repo    |     RSS
MD's Technical Sharing



Thursday, September 4, 2008

Change ComboBox.Text property in SelectedIndexChanged event

It seems that you can't change the Text property of a combobox inside SelectedIndexChanged event. The .Text will still contain the old value after the change due to cross-threading issues:

Workaround: Use delegation to do this, this will change the text right after the SelectedIndexChanged event:


this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.BeginInvoke(new ChangeTextDelegete(ChangeText));
}

private delegate void ChangeTextDelegete();
public void ChangeText()
{
this.comboBox1.Text = "Changed";
}


Problem: With this approach, sometimes "Exception has been thrown by the target of an invocation" fires randomly.


Reference:

How to change combobox text property after SelectedIndexChanged event?

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.