views:

1382

answers:

7

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: 

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

Martin Robins
A: 

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.

Dillie-O
+1  A: 

Move your change code outside of combobox event:

if(some condition)
{
    BeginInvoke(new Action(() => comboBox.Text = "new string"));
}
arbiter
A: 

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.

Daniel Pryden
+4  A: 

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

Chalkey
A: 

I have the same issue and the code

BeginInvoke(new Action(() => comboBox1.Text = text));

returns a compiler error (invalid expression term). Is this something native to VS2008 (I'm using VS2005) or do I simply miss some crucial namespace? Here are the ones in the current file:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
Pedery
A: 

Thanks a lot Chalkey, you have solved my lingering problem.

csharpuser
use a comment rather than add an "answer"
McBainUK