vb.net - Better to use SelectedIndex or SelectedItem for ComboBox? -


lets have combobox values "one, two, three"

as general rule, when testing conditional events based on combobox selection, better reference combobox.selecteditem or combobox.selectedindex?

if (combobox.selecteditem = "one")  

or

if (combobox.selectedindex = 0) 

or neither have advantage on other?

i find selectedindex easier use because can work on number , when there no selection don't have handle null. selecteditem null , should remember when trying access property.

usually selecteditem , selectedindex used inside selectedindexchanged event , easy forget nothing possibility

dim curvalue = combo.selecteditem.tostring() ' <- possible nullreferenceexception'   ..... 

however, if talking comparison there small advantage selectedindex because there no loading , testing of 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 in realm of micro-optimizations and, said in comment, use more readable you.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -