what is the .net code for adding year in this form like 2001-2002,2002-2003, in dropdown with the asp.net

Dani AI

Generated

asked how to fill a DropDownList with year ranges like 2001-2002. started by adding items in Page_Load and suggested a for loop — combine both ideas but add a couple of practical safeguards: only populate once (use !IsPostBack), generate the string YYYY-YYYY+1 in a loop, and set a useful Value (usually the start year as an integer) so you can use it easily in SQL.

A concise server-side pattern (C#) looks like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        int startYear = 2001;
        int lastStartYear = DateTime.Now.Year - 1; // change to DateTime.Now.Year if you want to include the next pair
        for (int y = startYear; y <= lastStartYear; y++)
        {
            string text = y + "-" + (y + 1);
            DropDownList1.Items.Add(new ListItem(text, y.ToString()));
        }
    }
}

Notes and gotchas: store the start year as the Value (e.g., 2001) so reading it is simple: int start = int.Parse(DropDownList1.SelectedValue); — then pass start to a parameterized SQL query. If the control is also data-bound elsewhere, use AppendDataBoundItems="true" or populate before calling DataBind() to avoid losing items. For academic or fiscal years that begin mid-calendar, adjust the lastStartYear logic using DateTime.Now.Month so ranges reflect your institution’s cutoff. To show the newest ranges first, loop downward.

These adjustments prevent duplicate items on postback, keep values SQL-friendly, and make the dropdown easy to use in queries and UI logic.

Recommended Answers

All 2 Replies

protected void Page_Load(object sender, EventArgs e)
    {
        this.DropDownList1.Items.Add("Orange");
        this.DropDownList1.Items.Add("Grapes");
        this.DropDownList1.Items.Add("Apple");
        this.DropDownList1.Items.Add("Mango");
        this.DropDownList1.Items.Add("Lemon");
        this.DropDownList1.Items.Add("Banana");

}

That can also be done in a simple for loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.