user1930845
user1930845

Reputation:

DropDownList exception Item not on the list?

    Dim Usr_Account_Question As String = "Your favorite teacher?"

    DropDownListQuestion.SelectedValue = Usr_Account_Question
    DropDownListQuestion.DataBind()

I am using VB.net and keep getting error that the item is not on the list. What I am trying to do is select an item from the list depending on the string in Usr_Account_Question. Could be in the middle of the list or the first item but it will be part of the drop down list selection.

Am I missing some code? When I replace Usr_Account_Question with "2" or "3" it works the item on the list is selected but not when I have a string.

UPDATE:

I actually solved it later. Just did not have time to update this post. Here is what I did.

Call DataBind on a list so we have data available, then pass in the string that is part of the list, it has to be exact.

' Data bind here
DropDownListQuestion.DataBind()    

' This is a string that is part of a Drop Down List
Dim Usr_Account_Question as String = "Your favorite teacher?"     
DropDownListQuestion.Items.FindByText(Usr_Account_Question).Selected = True

Put this in a page load so that way the list will be set to the option specified in a string.

Upvotes: 1

Views: 152

Answers (1)

BaSsGaz
BaSsGaz

Reputation: 784

Perhaps you should set DropDownListQuestion.SelectedItem instead of DropDownListQuestion.SelectedValue

You may want to check this answer to know the difference between .SelectedItem and .SelectedValue.

Upvotes: 1

Related Questions