views:

2106

answers:

3

What is the fastest way to fill ComboBox in C#?

  1. With Add()
  2. Bind the ComboBox to Dataset

Or there is a faster way ?

Thanks.

A: 

Well, using databinding is much less code for anything other than one item:

myComboBox.DataSource = myDataSet; myComboBox.DataBind();

Of course, this assumes your DataSet already contains data. Perhaps you could refine your question?

BobbyShaftoe
A: 

Your fastest way will probably be either binding to a DataReader or iterating over a DataReader and using the Add() method of the ComboBox. Either way, the key isn't whether you're binding or iterating (I haven't instrumented those and therefore can't tell you which is faster), the key is using the DataReader.

By using a DataSet, you're loading and populating a fairly heavy data object. If you're noticing speed issues, this is probably the culprit. Just switching to DataReader (whether using Add() or binding) will probably get you a boost.

Of course, all this is assuming you're seeing a speed issue in the first place. If you're not, and no one's complaining about the speed of your app, and your app doesn't have a projected growth that would cause an issue, then stay on your current path! "Premature optimization is the root of all evil."

John Rudy
+1  A: 

You'll probably find that the fastest way of doing this will be to read the DB from a datareader, then call .Add() in a loop, but using the DataReader's numerically indexed fields (instead of the named properties).

Dave Markle
We should also note that combining the UI and DB code (while being technically the fastest) is probably not the most elegant means of doing this. Separating out the layers is worth the slight overhead.
Quibblesome