Creating The Dynamic Dropdown – Generating a Year Pick List

I had created a .net form that produced reports by year through the use of a dropdown list.  The user asked if the drop down list could be changed to display the current year.  I wanted to provide this functionality without having to make this change year after year, so I had to include code that addressed that issue.  Here is how I did that.

Add the drop down list to  the .net form.

<form id=”form1″ runat=”server”>
<p style=”text-align: center”> <asp:DropDownList ID=”drpYear” runat=”server”></asp:DropDownList></p>

On the code behind form, enter the following code.

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
int currentYear = DateTime.Now.Year;
int fromYear = 2009;

for (int i = fromYear; i <= currentYear; i++)
this.drpYear.SelectedItem.Text = currentYear.ToString();
this.drpYear.SelectedValue = currentYear.ToString();

That’s all there is to it.  The fromYear variable contains the the year that you want to start with in your drop down.




Leave a Reply

Your email address will not be published. Required fields are marked *