asp.net dropdown list findbytext

I am using the following to select have the dropdown list select an item from the list:

    ddlIndustry.Items.FindByText("Trucking").Selected = true;

Is there another logic for doing this.

I noticed if I do:

   ddlIndustry.Items.FindByText("Trucking").Selected = true;

and then down the code do something like:

   ddlIndustry.Items.FindByText("Cards").Selected = true;

I get an error saying cannot select multiple items.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is what you want to do:

ddlIndustry.SelectedValue = ddlIndustry.Items.FindByText("Cards").Value;

The problem is that making ListItem as Selected does not clear selection of other ListItems. Keep in mind that Items property is a ListItemColletion, which is also used in ListBox and CheckListBox, which allow multiple item selection (while DropDownList does not allow that, which is why you got the error).

Using the SelectedValue propery of the DropDownList takes care of the multi-selection for you, unselecting previously selected items and selecting the new item by value.

You can check for a correlated issue here: https://stackoverflow.com/a/16068632/570191

Method 2

Try using ClearSelection to clear previous selection:

ddlIndustry.ClearSelection();
if (ddlIndustry.Items.FindByText("Cards") != null)
    ddlIndustry.Items.FindByText("Cards").Selected = true;

Method 3

This works for me, where the other syntaxes would not. (VB asp.net)

                Try
                    MyDropdownList.SelectedValue = ValueVariable 

                Catch ex As Exception

                End Try


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x