How to dynamically set Date , Month ,Year in drop down list in asp.net c#

In this article, I have bind the date, month and year from code behind (means we use c#).

Design:-



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

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <fieldset style="width: 300px;">
        <legend>Dynamically Bind Date,Month,Year</legend>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:DropDownList ID="ddldate" runat="server">
        </asp:DropDownList>
        <asp:DropDownList ID="ddlmonth" runat="server">
        </asp:DropDownList>
        <asp:DropDownList ID="ddlyear" runat="server">
        </asp:DropDownList>
    </fieldset>
    </form>
</body>
</html>

Code-behind(c#)

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Services;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        date();
        month();
        Year();
    }

    public void date()
    {
        for (int i = 1; i <= 31; i++)
        {
            ddldate.Items.Add(i.ToString());
        }
    }

    private void month()
    {
        DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
        for (int i = 1; i < 13; i++)
        {
            ddlmonth.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));
        }
    }


    protected void Year()
    {

        for (int i = 2010; i <= 2025; i++)
        {
            ddlyear.Items.Add(i.ToString());
        }
        ddlyear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true;

    }


}


Out-Put:-



How to dynamically set Date , Month ,Year in drop down list in asp.net c# How to dynamically set Date , Month ,Year in drop down list in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 2:22:00 PM Rating: 5

No comments:

Powered by Blogger.