How to fill dropdownlist with days, month and year
Introduction: In previous article i explained How to fill DropDownList from Sql server database in asp.net and how to Fill CheckBoxList based on DropDownList selection in asp.net(C#, VB) and How to open Pop up window on Drop down selection in Asp.net. Now in this article I am going to explain one of the common requirements while creating user input form like registration form where user has to select his date of birth, joining date etc. So here in this example I have demonstrated how to fill year, month and day in theDropDownList . Current date will be selected in the DropDownList by default and when user select another month from the DropDownList then corresponding number of days will be filled in the days DropDownList.
- In the design page(.aspx) place 3 DropDownList for year, month and days as:
<fieldset style="width:300px">
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">
</asp:DropDownList>
</fieldset>
- In the Code behind file(.aspx.cs) write the code as:
C#.NET Code
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();
}
FillDays();
}
This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it,
ReplyDelete加拿大cs代写