[英]Select Day, Month and Year Date from DropDownList in C#
我使用此代码在 ASP.Net 中使用三个 DropDownList 填充我自己的日、月和年日期选择器
现在我需要将每个 DDL 的默认值设置为DateTime.MinValue
的 vakue ,即01/01/0001
,因为要记录在数据库中的日期值并不总是可用的:
ddlday
我需要作为默认值: 01
;ddlMonth
我需要作为默认值: January
;ddlYear
我需要作为默认值: 0001
;使用此代码我没有错误,但是:
ddlday
我有默认值: 01
;ddlMonth
我有默认值: january
;ddlYear
我有默认值: 2019
;请问你能帮我吗?
我的代码如下。
代码隐藏
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime dateofBirth = DateTime.MinValue;
ddlMonth.DataSource = Enumerable.Range(1, 12).Select(a => new
{
MonthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(a),
MonthNumber = a
});
ddlMonth.DataBind();
ddlYear.DataSource = Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse();
ddlYear.DataBind();
ddlday.SelectedValue = dateofBirth.Day.ToString();
ddlMonth.SelectedValue = dateofBirth.Month.ToString();
ddlYear.SelectedValue = dateofBirth.Year.ToString();
ddlday.DataSource = Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(ddlMonth.SelectedValue)));
ddlday.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
ddlday.DataSource = Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(ddlMonth.SelectedValue)));
ddlday.DataBind();
}
}
标记
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sc" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td>
<asp:UpdatePanel ID="updpnlDay" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddlday" runat="server">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
<asp:UpdatePanel ID="updpnlMonth" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddlMonth" runat="server" AutoPostBack="true" DataTextField="MonthName"
DataValueField="MonthNumber" OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:DropDownList ID="ddlYear" runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
但是您的 ddlYear 没有值 1,只有 1920 到 2019 范围内的年份。您的意思是在该范围内包含最小年份吗?
ddlYear.DataSource = Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse().Append(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.