ComboBox.Item.AddRange(string[]) VS. ComboBox.DataSource = string[]

Viewed 1349

So, I have two options:

aComboBox.Item.AddRange(stringArray);
aComboBox.SelectedItem = stringFromStringArray;

and

aComboBox.DataSource = stringArray;
aComboBox.SelectedItem = stringFromStringArray;

Now, the first one is waaaaay slower when it comes to initialization (about 5-6 times). It does set the selected item properly, but still, it's very slow so I decided to go with the second one.

But, if I use the second one, the Items array within the aComboBox is not yet set when the second command is executed, so the selected item is the one at index 1, instead the one specified.

The question is, how do I get the performance of the second one with the functionality of the first one?

EDIT:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ComboBoxTest
{
class MainWindow : Form
{
    string[] list = new string[1548];
    TableLayoutPanel panel = new TableLayoutPanel();

    public MainWindow() : base()
    {
        Height = 2000;
        Width = 1000;

        Random rand = new Random();

        for (int i = 0; i < 1547; i++)
        {
            list[i] = rand.Next().ToString();
        }

        list[1547] = 5.ToString();

        Button button = new Button();
        button.Text = "Press me";
        button.Click += Button_Click;

        panel.Controls.Add(button, 0, 0);

        panel.Height = 2000;
        panel.Width = 1000;

        Controls.Add(panel);

        Show();
    }

    private void Button_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 36; i++)
        {
            ComboBox box = new ComboBox();
            box.DataSource = list;  //box.Items.AddRange(list);
            box.SelectedItem = 5.ToString();

            panel.Controls.Add(box, 0, i+1);
        }
    }
}
}

I reproduced the problem with this program. If you change it to addRange(), it will take a lot more time, but it will set the item.

Try adding a breakpoint to the SelectedItem and then look at the ComboBox. If you set the one, the other will be null (DataSource vs. Items). The ComboBox seems to look into Items to check if the string exists within the list, and that's why it fails with DataSource method.

Bonus question: Why are all ComboBoxes working as one (try changing the value)?

2 Answers
Related