C# ComboBox in DropDownList style, how do I set the text?


Question

I want to use a ComboBox with the DropDownList style (the one that makes it look like a button so you can't enter a value) to insert a value into a text box. I want the combobox to have a text label called 'Wildcards' and as I select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains 'Wildcard'. My first problem is I can't seem to set a text value when the combobox is in DropDownList style. Using the properties pallet doesn't work the text value is simply cleared when you click off, adding comboBox.Text = "Wildcards"; to form_load doesn't work either. Can anyone help?

1
19
8/23/2010 1:58:53 PM

Accepted Answer

The code you specify:

comboBox.Text = "Wildcards";

...should work. The only reason it would not is that the text you specify is not an item within the comboBox's item list. When using the DropDownList style, you can only set Text to values that actually appear in the list.

If it is the case that you are trying to set the text to Wildcards and that item does not appear in the list, and an alternative solution is not acceptable, you may have to be a bit dirty with the code and add an item temporarily that is removed when the drop-down list is expanded.

For example, if you have a form containing a combobox named "comboBox1" with some items and a button named "button1" you could do something like this:

private void button1_Click(object sender, EventArgs e)
{
    if (!comboBox1.Items.Contains("Wildcards"))
    {
        comboBox1.Items.Add("Wildcards");
    }

    comboBox1.Text = "Wildcards";
}

private void comboBox1_DropDown(object sender, EventArgs e)
{
    if (comboBox1.Items.Contains("Wildcards"))
        comboBox1.Items.Remove("Wildcards");
}

That's pretty quick and dirty but by capturing the DropDownClosed event too you could clean it up a bit, adding the "Wildcards" item back as needed.

33
2/8/2009 12:36:17 AM

You can select one of items on formload or in form constructor:

public MyForm()
{
    InitializeComponent();

    comboBox.SelectedIndex = 0;
}

or

private void MyForm_Load(object sender, EventArgs e)
{
    comboBox.SelectedIndex = 0;
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon