Search code examples
asp.netcomboboxselectedvalue

Is it a good practice to compare combobox.selectedvalue to a string?


I have a combo box and couple of text boxes in my web page, depending on combobox's selected value, I will set focus to specific text box. Following is my code:

        if (cbo1.SelectedValue == "01")
            txt1.Focus();
        else
            txt2.Focus();

This would work even when the combo box being just loaded and there is no selected item. My question is "is this a good practice?" since SelectedValue actually is an object. Normally I use cob1.SelectedValue.ToString(), but I got an exception when there is no selected item.


Solution

  • Good practice would be to declare a string constant:

    private const string FIRST_FIELD_VALUE = "01";
    
    (...)
    
        if (cbo1.SelectedValue.Equals(FIRST_FIELD_VALUE))
            txt1.Focus();
        else
            txt2.Focus();
    

    Otherwise, yes. I think comparing strings with strings is good practice.