Tuesday, January 7, 2014

Bind Year List in DropDownlist Using C# Code.

Here I am going to explain ,how to bind year list in dropdownlist  using c# code.
I use for_ loop to bind year list.

Demo : 

Loop for Bind year list :


 for (int i = DateTime.Now.Year; i > 1950; i--)

        {
              // drpyear is the DropDownlist Name
            drpyear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }


Full Code :

Copy and Paste the code in .aspx page 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bind DropDownlist Using For loop</title>
  
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
Select Year <asp:DropDownList ID="drpyear" runat="server" >
        </asp:DropDownList>
    
    </div>
    </form>
</body>
</html>

Go to .aspx.cs page and write the below code in Page Load

 protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = DateTime.Now.Year; i > 1950; i--)
        {
            drpyear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        drpyear.Items.Insert(0, "--Select Year--");
    }

   
If this code help you ,please share.

No comments:

Post a Comment