Quantcast
Viewing all articles
Browse latest Browse all 12583

Before handle created, insert a Item to a combobox causes its SelectedItem change

Create a form with a combobox, and in its constructor:

public Form1()
{
        InitializeComponent();

        comboBox1.Items.Add("aaa");
        comboBox1.Items.Add("bbb");
        comboBox1.SelectedItem = "bbb";
        MessageBox.Show(comboBox1.SelectedItem.ToString());
        comboBox1.Items.Insert(0, "000");
        MessageBox.Show(comboBox1.SelectedItem.ToString());
}

The first MessageBox show "bbb" and the second one show "aaa". However, when create the handle first:

public Form1()
{
        InitializeComponent();

        IntPtr h = comboBox1.Handle;      // Force create the handle

        comboBox1.Items.Add("aaa");
        comboBox1.Items.Add("bbb");
        comboBox1.SelectedItem = "bbb";
        MessageBox.Show(comboBox1.SelectedItem.ToString());
        comboBox1.Items.Insert(0, "000");
        MessageBox.Show(comboBox1.SelectedItem.ToString());
}

This time both MessageBox show "bbb".

Why?




Viewing all articles
Browse latest Browse all 12583

Trending Articles