Search code examples
c#asp.netdropdownbox

Is it better to set the SelectedValue of a drop-down list or to set the Selected property of the specific item?


For asp.net dropdownlist, both of the below lines of code achieve the same thing. The only difference I see is one is shorter than other. Is there a specific advantage of using one over the other other than code readability?

ddl.SelectedValue = 5;

vs.

ddl.Items.FindByValue(5).Selected = True;

Solution

  • Both items do most of the same things; however, the second line, if no item is found, will throw an exception:

    ddl.Items.FindByValue(5) //may return null..
                            .Selected = True; //throws NullReferenceException
    

    Whereas selectedvalue doesn't provide that hassle.