How to set a dropdownlist item as selected in ASP.NET?

后端 未结 5 1498
栀梦
栀梦 2020-12-04 23:58

I want to set selecteditem for asp. net dropdownlist control programmatically.

So I want to pass a value to the dropdownlist control to set the selected item where i

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 00:30

    You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.

    dropdownlist.ClearSelection();
    dropdownlist.Items.FindByValue(value).Selected = true;
    

    Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.

    Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.

    "Cannot have multiple items selected in a DropDownList"
    

提交回复
热议问题