Matthias Wuttke
Matthias Wuttke

Reputation: 2032

Unexpected ComboBox behaviour

Given the following code

namespace WindowsFormsApplication1
{
    public class Form1 : Form
    {
        public Form1()
        {
            comboBox1 = new System.Windows.Forms.ComboBox();

            comboBox1.Items.AddRange(new object[] {
            "Item 1",
            "Item 2",
            "Item 3"});
            comboBox1.Location = new System.Drawing.Point(93, 103);
            comboBox1.Name = "comboBox1";
            comboBox1.Size = new System.Drawing.Size(121, 21);
            comboBox1.Text = "Item 1"; // **line 1**

            ClientSize = new System.Drawing.Size(284, 262);
            Controls.Add(this.comboBox1);

            Name = "Form1";
            Text = "Form1";

            comboBox1.Text = "Nanu"; // **line 2**
        }

        private ComboBox comboBox1;

    }
}

I expected my ComboBox to display "Nanu" (DropDownStyle.DropDown), but it shows "Item 1". Omitting the line comboBox1.Text = "Item 1"; fixes this. Putting comboBox1.Text = "Nanu"; in the OnShown event handler also fixes the "bug".

Why is this?

Upvotes: 0

Views: 103

Answers (1)

GuFigueiredo
GuFigueiredo

Reputation: 635

According to msdn

Setting the Text property to null or an empty string ("") sets the SelectedIndex to -1. Setting the Text property to a value that is in the Items collection sets the SelectedIndex to the index of that item. Setting the Text property to a value that is not in the collection leaves the SelectedIndex unchanged.

So, when you do:

comboBox1.Text = "Item 1";

You are automatically selecting the "Item 1" previously added in the list of Items. Add "Nanu" to the collection and it should work :

comboBox1.Items.AddRange(new object[] {
    "Item 1",
    "Item 2",
    "Item 3",
    "Nanu"});

Upvotes: 2

Related Questions