Using the DropDownList Control in ASP.NET Web Forms: Creating and Populating Dropdown Lists

Learn how to use the DropDownList control in ASP.NET Web Forms to create and populate dropdown lists on your web pages. This tutorial explains how to add DropDownLists using Visual Studio and code, and how to add items to the dropdown list programmatically.



Using the DropDownList Control in ASP.NET Web Forms

Introduction to the DropDownList Control

The DropDownList control in ASP.NET Web Forms is a server-side control used to create a dropdown list on a web page. This control allows users to select a single item from a predefined list of options. It's a convenient way to provide users with a set of choices in a compact and user-friendly manner. The selected value is sent to the server when the form is submitted.

Creating a DropDownList Control

You can create a DropDownList using either the Visual Studio drag-and-drop interface or by writing the HTML code directly within your ASPX file. Here’s how you would create one using ASP.NET syntax:

Syntax

<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

After adding the DropDownList to your form, you can add items to the list using the Items property in Visual Studio. (A screenshot showing this process would be included here.)

Adding Items to the DropDownList

(A screenshot showing the process of adding items to the DropDownList using Visual Studio's property window would be included here.)

Example: Handling DropDownList Selection

This example shows how to handle the selection made from the dropdown list.

ASPX Code (DropDownListExample.aspx)

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropDownListExample._Default" %>
<form id="form1" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Text="Please Select" Value="" />
        <asp:ListItem Text="New Delhi" Value="New Delhi" />
        <asp:ListItem Text="Greater Noida" Value="Greater Noida" />
        <asp:ListItem Text="NewYork" Value="NewYork" />
        <asp:ListItem Text="Paris" Value="Paris" />
        <asp:ListItem Text="London" Value="London" />
    </asp:DropDownList><br />
    <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" /><br />
    <asp:Label ID="Label1" runat="server"></asp:Label>
</form>
C# CodeBehind (Default.aspx.cs)

using System;
using System.Web.UI;
namespace DropDownListExample
{
public partial class _Default : Page
{
protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = DropDownList1.SelectedValue == "" ? "Please Select a City" : "Your Choice is: " + DropDownList1.SelectedValue;
}
}
}
Output

(A screenshot showing the dropdown list and the output label displaying the selected city after the button click would be included here.)