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?
A ComboBox will bind to whatever object collection you specify, as opposed to simply having a text/value combination that you find in DropDownLists.
What you'll need to do is go into the ComboBox's Items collection, find the item you want to update, update whatever property you have being bound to the Text field in the ComboBox itself and then the databinding should automatically refresh itself with the new item.
However, I'm not 100% sure you actually want to modify the underlying data object being bound, so you may want to create a HashTable or some other collection as a reference to bind to your ComboBox instead.
Although it's in VB, this blogpost on Changing Combobox Text in the
SelectedIndexChanged
Event goes into a little more detail as to why you need to use a delegate as a workaround to change the ComoboBox Text. In short, .NET is trying to prevent an endless loop that could occur because 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
This code should work...
Hope it helps... :)