Objective:-Select Day Month Year Using DropDownList in ASP.NET.
STEPS :-
STEP:- 1 CREATE NEW PROJECT.
Go to File -> New -> Project -> Select asp.net web forms application -> Entry Application Name -> Click OK.
STEP:-2 Select Three(3) DropDownList from Toolbox for Date, Month and Year.
********HTML Code***************
<!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>Select Day Month Year By DropDownList</title>
</head>
<body>
<form id="form1" runat="server">
<fieldset style="width:385px">
<legend>Select Date</legend>
Year: <asp:DropDownList ID="ddlYear" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlYear_SelectedIndexChanged" ></asp:DropDownList>
Month: <asp:DropDownList ID="ddlMonth" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlMonth_SelectedIndexChanged">
</asp:DropDownList>
Day: <asp:DropDownList ID="ddlDay" runat="server"
onselectedindexchanged="ddlDay_SelectedIndexChanged">
</asp:DropDownList>
</fieldset>
</form>
</body>
</html>
********C# Code***************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Fill Years
for (int i = 2013; i <= 2020; i++)
{
ddlYear.Items.Add(i.ToString());
}
ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true; //set current year as selected
//Fill Months
for (int i = 1; i <= 12; i++)
{
ddlMonth.Items.Add(i.ToString());
}
ddlMonth.Items.FindByValue(System.DateTime.Now.Month.ToString()).Selected = true; // Set current month as selected
//Fill days
FillDays();
}
}
public void FillDays()
{
ddlDay.Items.Clear();
//getting numbner of days in selected month & year
int noofdays = DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue));
//Fill days
for (int i = 1; i <= noofdays; i++)
{
ddlDay.Items.Add(i.ToString());
}
ddlDay.Items.FindByValue(System.DateTime.Now.Day.ToString()).Selected = true;// Set current date as selected
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
FillDays();
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
FillDays();
}
}
}

No comments:
Post a Comment