How to create a DropDownList displaying years in asp.net
23 December 2022

How to create a DropDownList displaying years in asp.net

By

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


   <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>
_____________________________________________
<script runat="server">   
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text = "you selected....<br />";
        Label1.Text += DropDownList1.SelectedItem.Text;
    }
</script>  
_____________________________________________
        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;
            }

        }
Prev Post

ចង់រៀន IT តើត្រូវមានមូលដ្ឋានគ្រឹះអ្វីខ្លះ?

Next Post

តើ Internet និង World Wide…

post-bars