In this blog post, I will share a quick tip that showcases you the best way to check if the dropdown list contains a value or check if dropdownlist is empty in C#. Previously I have explained How to get html textbox value in ASP.Net
Check if dropdown has selected value C# ASP.Net
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.
Find the below source code to check if dropdown list contains value in C#:-
<%@ 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 }
You may also like:
Leave a Reply