Reputation: 53243
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
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
Reputation: 46047
I usually prefer to use SelectedValue
:
DropDownList1.SelectedValue = "Foo";
Upvotes: 0
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