views:

88

answers:

4

I use comboboxes a lot. I often loop through them to find a match based upon the SelectedValue, for example...

while(cmbCompany.SelectedValue.ToString()!=B1ID)
{ 
    cmbCompany.SelectedIndex++; 
}

a) am I missing some much quicker option!
b) if my comparison was against an integer, is there any benefit in declaring a string and setting that equal to the integer.ToString(), or if I just (in my example above) used B1ID.ToString() would the compiler optimise it for me?
c) or are string comparisons so slow that I'd be better off parsing (or casting) the SelectedValue to an integer?

+1  A: 

cmbCompany.SelectedValue = B1ID ought to do the trick - does it not?

Will A
Not if SelectedValue needs converting to a string to match B1ID
Martin Harris
Better to convert B1ID to something that'll match SelectedValue then.
Will A
thanks I hadn't realised I could use it that way round, I would have expected that to set the currently selected items value to B1ID, I now feel quite stupid, still we all have to learn. Sometimes the language is more 'intelegent' than I expect.
Graham
No problem - I'm always coming across quicker ways of doing something I've been doing the slow way for years. :)
Will A
A: 

a) Maybe, but I'll let others answer that part.

b) The compiler doesn't seem likely to hoist the ToString out of the loop.

c) Definitely slower to reparse each value. Better to compare strings.

Steven Sudit
A: 

a/b) Have you tried using FindString? The method basically looks for something that *starts with (there is an equivelent one for Find exact).

Or you could search the "items" and do FindByValue

  cmbCompany.Items.FindByValue

c) Built in methods will be faster, as well as using native types (aka its more costly to cast and then compare)

Nix
+8  A: 

There are a number of ways, and yes, what you are doing is very inefficient.

Here is a better (though rough) code sample from MSDN:

int index = comboBox1.FindString(textBox2.Text);
comboBox1.SelectedIndex = index;

(Notice that this code snippet looks for the data in the collection first and then sets the SelectedIndex value.)

The most confounding part of your algorithm is that you're incrementing the index with every comparison. This is very dangerous and inefficient because you actually change the selection with every test which also fires events (if you have them wired) reacting to the selection change and could confound your logic down the line.

Paul Sasik
fabulous, thanks, yes I have to turn the events off and back on again, which i always thought was inneficient.I've used FindStringExact to check for 'new' items typed into the comboboxes, but didn't realise I couled get the index back.I now have a lot of changes to make :)
Graham