check if dropdownlist contains value c#

Keyboard | check if dropdownlist contains value c#, how to check if dropdownlist contains value in c#

Check if dropdownlist Contains Value C#

DropDownList represents a control that allows the user to select a single item from a drop-down list. To specify the items that you want to appear in the DropDownList control, place a ListItem object for each entry between the opening and closing tags of the DropDownList control.

In this blog post, you’re going to learn how to check if dropdownlist contains value or check if dropdownlist is empty C#. There are a couple ways to check: some people are looping through all items and finding the item exists or not. The following example will demonstrate the best way to check if a drop-down list contains a value or not.

How to check if dropdownlist contains value in C#

Find the dot net source code below:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Best way to check if a drop down list contains a value</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>Check if dropdownlist contains value</h2>
            <asp:DropDownList ID="ddlTest" runat="server">
                <asp:ListItem Text="Select"></asp:ListItem>
                <asp:ListItem Value="ABC"></asp:ListItem>
                <asp:ListItem Value="XYZ"></asp:ListItem>
            </asp:DropDownList>
        </div>
    </form>
</body>
</html>

using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ddlTest.Items.FindByValue("XYZ") != null)
        {
            ddlTest.SelectedIndex = 2;
        }
    }
}

OR

if (ddlMobileNumber.Items.FindByText(
    GetMobileNumberCookie().ToString()) != null)
    {
      // .. your code here
    }

OR

if (ddlMobileNumber.Items.Contains(new 
    ListItem(GetMobileNumberCookie().ToString())))
     {
         // .. your code here
     }

Download Source code

What do you think?

I hope you liked this article on How to check if DropDownList Contains Value. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

LEAVE A REPLY

Please enter your comment!
Please enter your name here