[c#] 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;

This question is related to c# asp.net drop-down-menu

The answer is


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

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

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

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

That will return an item. Simply change to:

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

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.


If the function return Nothing, you can try this below

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

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){}

//you can use the ? operator instead of if

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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu