views:

37

answers:

2

I have the following code:

List<string> list = SomeFunction();
this.myComboBox.DataSource = list;

For some reason, the assignment to DataSource is taking a surprising amount of time (about 1.4 seconds), when the list only contains 4 items.

Any idea why this is?

Edit:

SomeFunction() looks in several folders on disk for the existence of a particular .xml file, and if it exists, puts the containing folder name into the list which it returns.

Investigation:

I stuck a call to DateTime.Now around the DataSource assignment, and it comes back at ~1400ms each time. This leads me to believe that it is purely the DataSource assignment that causes it. However, I created a dummy List; Add()ing strings directly to it. This datasource executes in ~200ms. So perhaps it is not the DataSource assignment after all, and has something to do with SomeFunction. However, then I tried just inserting the strings one by one, and it executes in ~0ms.

A: 

Try direct assign of your function to ComboBox.

eg: this.myComboBox.DataSource=SomeFunction();

Vyas
A: 

It was in the SelectedIndexChanged event handler, where I was loading a file. It turns out that an assignment to the DataSource member will automatically change SelectedIndex (presumably back to 0, if it exists), whereas calling Items.Add will not do so.

In my case, it was a problem because I wanted to manually choose which item to load, and so it was loading twice - once automatically because of the event caused by the assignment (undesired) and once manually.

Smashery
The reason the dummy list was so fast is because they weren't file names that existed, so the event handler didn't do anything.
Smashery
However, the general outline of the code from SomeFunction would still have been helpful (as well as any other code interacting with the combo box at that time, like the SelectedIndexChanged you mentioned), simply because it was possible (this was my first thought) that the function returns a lazy IEnumerable (linq) that is evaluated while it is accessed rather than when the function returns.
Alex Paven