Monday 10 March 2014

Retrieving Value From SelctionOption List

Hi Guys 
I am going to share about one issue which I have come across.  I was just  comparing some value of selectOption list by iterating that list.

Here is the code:-
list<SelectOption> listOfOptions;
listOfOptions = new list<SelectOption>();
listOfOptions.add(new SelectOption('a','a') );
listOfOptions.add(new SelectOption('1','1') );
listOfOptions.add(new SelectOption('A','A') );
listOfOptions.add(new SelectOption('@','@') );
for(SelectOption option:listOfOptions){
   if(option== 'A'){
        System.debug('hi');
   }
}
COMPILE ERROR: Comparison arguments must be compatible types: System.SelectOption, String

To avoid this error we need to use getValue() method.
list<SelectOption> listOfOptions;
listOfOptions = new list<SelectOption>();
listOfOptions.add(new SelectOption('a','a') );
listOfOptions.add(new SelectOption('1','1') );
listOfOptions.add(new SelectOption('A','A') );
listOfOptions.add(new SelectOption('@','@') );
for(SelectOption option:listOfOptions){
   if(option.getValue()== 'A'){
        System.debug('hi');
   }
}
Now 'Hi' will be printed two times.You can run this code from workbench and developer console. Let me know if some error is there by adding comments. 

No comments: