How to create a DropDownList displaying years in asp.net

ASP.NET DropDownList Years
The following asp.net c# example code demonstrate us how can we display a list of years in a DropDownList server control. Many web developers want to avoid TextBox to collect a year from web users. To select a year from DropDownList is very easy and error free way. Web visitors can select a year from a drop down list without writing content on TextBox control.

In the bellow example code, we populated a DropDownList with 11 years. We populated the DropDownList with previous 5 years and future 5 years and current year based on the current year. At first we create a variable to hold the current year from system DateTime object. Then we subtract 5 years and Add 5 years with the present year integer value to loop through it. Finally, DropDownList render items with 11 years.
dropdownlist-years.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  
    
<!DOCTYPE html>
      
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    { 
        if(!Page.IsPostBack)
        {
            int year = DateTime.Now.Year;
            for (int i = year - 5; i <= year + 5; i++)
            {
                ListItem li = new ListItem(i.ToString());
                DropDownList1.Items.Add(li);
            }
            DropDownList1.Items.FindByText(year.ToString()).Selected = true;
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text = "you selected....<br />";
        Label1.Text += DropDownList1.SelectedItem.Text;
    }
</script>      
      
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>asp.net dropdownlist years</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - dropdownlist years
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="select an item from dropdownlist."
            Font-Size="X-Large"
            Width="350"
            >      
        </asp:Label>      
        <br /><br />
        <asp:DropDownList
            ID="DropDownList1"
            runat="server"
            AutoPostBack="true"
            Width="350"
            Font-Size="X-Large"
            OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
            >
        </asp:DropDownList>
    </div>      
    </form>      
</body>      
</html>
More asp.net examples