GLP
GLP

Reputation: 3685

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.

Upvotes: 0

Views: 2219

Answers (2)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

Add this condition

 if( cbo1.SelectedIndex > 0)
 {
       if (cbo1.SelectedValue == "01")
            txt1.Focus();
        else
            txt2.Focus();
 }

Upvotes: 0

Francis P
Francis P

Reputation: 13665

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.

Upvotes: 1

Related Questions