How to Dynamically Add years in Drop down list in asp.net c#

In this article, I will bind the dropdownlist with years dynamically. Many time we need to add years in drop down list so we fetch the values from database or enter the front end , suppose if we have 40 years for adding that’s means it will take so much for removing this problem we can use below code.


Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dynamiciallybindyear.aspx.cs" Inherits=" dynamiciallybindyear " %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:DropDownList ID="DropDownList1" runat="server" >
        </asp:DropDownList>
   
    </div>
    </form>
</body>
</html>


Code behind(c#):-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

public partial class dynamiciallybindyear: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
Year();

    }


    protected void Year()
    {

        for (int i = 2010; i <= 2025; i++)
        {
            DropDownList1.Items.Add(i.ToString());
           

        }
        DropDownList1.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true;
    }

 }


Out-Put:-


How to Dynamically Add years in Drop down list in asp.net c# How to  Dynamically Add years in Drop down list in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 2:23:00 PM Rating: 5

1 comment:

  1. protected void abc()
    {
    int a = DateTime.Now.Year;
    int b=a-60;
    while (b<=a)
    {
    D3.Items.Add(b.ToString ());
    b = b + 1;

    }
    D3.Items.Insert(0, "Year");

    }

    ReplyDelete

Powered by Blogger.