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

C#asp.netDrop Down-Menu

C# Problem Overview


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;

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

That will return an item. Simply change to:

if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)
    ddlCustomerNumber.SelectedIndex = 0;

Solution 3 - C#

If 0 is your default value, you can just use a simple assignment:

ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();

This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.

I use this mechanism quite a lot and find it very handy.

Solution 4 - C#

What about this:

ListItem match = ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString());
if (match == null)
    ddlCustomerNumber.SelectedIndex = 0;
//else
//    match.Selected = true; // you'll probably select that cookie value

Solution 5 - C#

On C# this works:

        if (DDLAlmacen.Items.Count > 0)
        {
            if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
            {
                DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
            }
        }

Update:

Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."

So. for this to work on Visual Basic, I had to change the code like this:

        If DDLAlmacen.Items.Count > 0 Then
            If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
                DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
            End If
        End If

Solution 6 - C#

ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
    ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}

Solution 7 - C#

You could try checking to see if this method returns a null:

if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
    ddlCustomerNumber.SelectedIndex = 0;

Solution 8 - C#

//you can use the ? operator instead of if

ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";

Solution 9 - C#

If the function return Nothing, you can try this below

if (ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString()) != Nothing)
{
...
}

Solution 10 - C#

Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):

if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustenView Question on Stackoverflow
Solution 1 - C#Scott AndersonView Answer on Stackoverflow
Solution 2 - C#Nathan WheelerView Answer on Stackoverflow
Solution 3 - C#TobiasView Answer on Stackoverflow
Solution 4 - C#Rubens FariasView Answer on Stackoverflow
Solution 5 - C#NathanView Answer on Stackoverflow
Solution 6 - C#Vijaya Krishna TummalaView Answer on Stackoverflow
Solution 7 - C#Andy RoseView Answer on Stackoverflow
Solution 8 - C#Alejandro HaroView Answer on Stackoverflow
Solution 9 - C#Mia ZhangView Answer on Stackoverflow
Solution 10 - C#estinamirView Answer on Stackoverflow