Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a drop down list contains a value?

When the user navigates to a new page, this ddl's selected index is determined by a cookie, but if the ddl doesn't contain that cookie's value, then I'd like it to be set the 0. What method would I use for the ddl? Is a loop the best way, or is there a simply if statement I can perform?

This is what I've attempted, but it doesn't return a bool.

if ( !ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString() ) )     ddlCustomerNumber.SelectedIndex = 0; 
like image 470
Justen Avatar asked Jan 05 '10 15:01

Justen


People also ask

How do you find the drop down value?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

What is selected value in Dropdownlist?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

What is the difference between drop down list and list box?

A standard list box is a box containing a list of multiple items, with multiple items visible. A drop-down list is a list in which the selected item is always visible, and the others are visible on demand by clicking a drop-down button.


2 Answers

There are two methods that come to mind:

You could use Contains like so:

if (ddlCustomerNumber.Items.Contains(new      ListItem(GetCustomerNumberCookie().ToString()))) {     // ... code here } 

or modifying your current strategy:

if (ddlCustomerNumber.Items.FindByText(     GetCustomerNumberCookie().ToString()) != null) {     // ... code here } 

EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.

like image 129
Scott Anderson Avatar answered Oct 05 '22 00:10

Scott Anderson


That will return an item. Simply change to:

if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)     ddlCustomerNumber.SelectedIndex = 0; 
like image 45
Nathan Wheeler Avatar answered Oct 04 '22 23:10

Nathan Wheeler