Dropdown : Use FindByText or FindByValue to select item in dropdown

Dropdown : Use FindByText or FindByValue to select item in dropdown

You have added a dropdownlist to webpage with ID = ddlAccomodations

Avoid using :

ddlAccomodations.SelectedValue = strText;

If strText is not there in dropdown , it will throw a runtime error.

Hence use below code :

VB.NET

If Not IsNothing(ddlAccomodations.Items.FindByText(Convert.ToString(strText))) Then

            ddlAccomodations.Items.FindByText(Convert.ToString(strText)).Selected = True

End If

C#

if ((ddlAccomodations.Items.FindByText(Convert.ToString(str)))!=null)

            {

            ddlAccomodations.Items.FindByText(Convert.ToString(str)).Selected = true;

            }

Leave a Reply