pencilCake
pencilCake

Reputation: 53243

What is the correct way to change selection of a DropDownList?

I am having a problem to change a selected item in a drop-down.

The way I use is (a property in the code behind which sets the new selection):

public char Candy
{
set
    {

        var newSelection = ddlCandy.Items.FindByValue(value.ToString());
        ddlCandy.ClearSelection();
        newSelection.Selected = true;

    }
}

Is this a recommended and proper way?

Upvotes: 1

Views: 242

Answers (3)

Damith
Damith

Reputation: 63065

Safe way is fist Find the given item from DropDownList and set it as SelectedValue

ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
if(oListItem != null)
{
 DropDownList1.SelectedValue = oListItem.Value;
}

if you directly assign SelectedValue it may through an exception if it is not exist in the list like bellow.

'DropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.

Upvotes: 1

James Johnson
James Johnson

Reputation: 46047

I usually prefer to use SelectedValue:

DropDownList1.SelectedValue = "Foo";

Upvotes: 0

Davide Piras
Davide Piras

Reputation: 44605

recommended approach is to simply assign the SelectedValue property with the Value you have and the DropDownList control will find and select the proper item for you, if any.

Upvotes: 2

Related Questions