Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to use SelectedIndex or SelectedItem for ComboBox?

Tags:

vb.net

Lets say I have a ComboBox with the values "One, Two, Three"

As a general rule, when testing for conditional events based on the ComboBox selection, would it be better to reference the ComboBox.SelectedItem or ComboBox.SelectedIndex?

If (ComboBox.SelectedItem = "One") 

or

If (ComboBox.SelectedIndex = 0)

Or does neither have an advantage over the other?

like image 989
Stas Bukhtiyarov Avatar asked Jan 13 '23 10:01

Stas Bukhtiyarov


1 Answers

I find SelectedIndex easier to use because you can work on a number and when there is no selection you don't have to handle the null. SelectedItem could be null and you should remember this when trying to access that property.

Usually SelectedItem and SelectedIndex are used inside a SelectedIndexChanged event and it easy to forget the Nothing possibility

Dim curValue = Combo.SelectedItem.ToString() ' <- Possible NullReferenceException'
  .....

However, if we are just talking about comparison then there is a very small advantage for SelectedIndex because there is no loading and testing of a string.

ComboBox b = new ComboBox();
if(b.SelectedItem == "One")
  Console.WriteLine("OK");
if(b.SelectedIndex == 0)
  Console.WriteLine("OK");

IL Code

IL_0000:  newobj      System.Windows.Forms.ComboBox..ctor
IL_0005:  stloc.0     // b
IL_0006:  ldloc.0     // b
IL_0007:  callvirt    System.Windows.Forms.ComboBox.get_SelectedItem
IL_000C:  ldstr       "One"
IL_0011:  bne.un.s    IL_001D
IL_0013:  ldstr       "OK"
IL_0018:  call        System.Console.WriteLine
IL_001D:  ldloc.0     // b
IL_001E:  callvirt    System.Windows.Forms.ListControl.get_SelectedIndex
IL_0023:  brtrue.s    IL_002F
IL_0025:  ldstr       "OK"
IL_002A:  call        System.Console.WriteLine

But we are in the realm of micro-optimizations and, as said in a comment, use what is more readable for you.

like image 96
Steve Avatar answered Feb 19 '23 01:02

Steve