Question

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.

Was it helpful?

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.

OTHER TIPS

Add this condition

 if( cbo1.SelectedIndex > 0)
 {
       if (cbo1.SelectedValue == "01")
            txt1.Focus();
        else
            txt2.Focus();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top