【问题标题】:Insert a date into a textbox and then that date would be selected in the calendar asp.net c#将日期插入文本框,然后在日历中选择该日期 asp.net c#
【发布时间】:2013-11-05 11:18:01
【问题描述】:

我需要知道是否可以在文本框中插入日期,然后在日历中选择该日期。我在 Microsoft Visual Studio Express 2012 for Web 中使用日历。

下面是通过选择日历上的日期将日期插入文本框的代码。 (但我想做相反的事情)

默认.aspx

<%@ 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">
<div>
    <asp:Calendar ID="Calendar1" runat="server" Visible="False" OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">PickDate...</asp:LinkButton>
</form>

默认.aspx.cs

using System;
using System.Collections.Generic;
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)
{

}
protected void LinkButton1_Click(object sender, EventArgs e)
{
    Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{


    TextBox1.Text = Calendar1.SelectedDate.ToLongDateString();


    Calendar1.Visible = false;

}
}

谢谢

【问题讨论】:

  • 您可以使用相同的属性SelectedDate 来指定应选择哪个日期。有什么问题,您在客户端需要它还是解析日期有问题?

标签: c# asp.net calendar


【解决方案1】:

怎么样

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    Calendar1.SelectedDate = Convert.ToDateTime(TextBox1.Text);
}

【讨论】:

  • 值得一提的是,在textbox 上有一个验证器,并在修改SelectedDate 之前检查有效性,因此不会出现任何令人讨厌的错误。
【解决方案2】:
 protected void LinkButton1_Click(object sender, EventArgs e)
    {
        if(TextBox1.Text!=string.Empty)
            Calendar1.SelectedDate = Convert.ToDateTime(TextBox1.Text);

        Calendar1.Visible = true;
    }

但是在将文本框值转换为日期时间之前,您需要验证用户输入的日期时间。这是javascript的链接datetime validation.

【讨论】:

    【解决方案3】:

    在文本框上为文本更改创建一个事件

    在事件中检查文本是否是处理异常的实际日期时间

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
      DateTime curDate = DateTime.Now;
      if (DateTime.TryParse(TextBox1.Text, out curDate))
      {
        Calendar1.SelectedDate = Convert.ToDateTime(TextBox1.Text);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多