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

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.


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;
}

Tags:

C#

.Net

Combobox