简体   繁体   English

阻止用户输入大于C#的起始日期

[英]Prevent user from entering a from date greater than to date c#

I am searching data based on two dates a from field and a To field in Asp.net 我正在基于Asp.net中的两个日期a从字段和到字段搜索数据

I want to prevent the user from entering a From date greater than a To date and display a message to the user Please select a valid date range 我要防止用户输入大于日期的“开始”日期并向用户显示一条消息,请选择一个有效的日期范围

  DateTime InvoiceDateFrom = new DateTime();
DateTime InvoiceDateTo = new DateTime();

if (TxtInvoiceDateFrom.Text.Trim() != "")
{

  //DateTime FromDate = DateTime.ParseExact(TxtInvoiceDateFrom.Text.Trim(), "dd/MM/yyyy", null).AddDays(1);
  InvoiceDateFrom = Convert.ToDateTime(TxtInvoiceDateFrom.Text);
  //DateTime toDate = DateTime.ParseExact(TxtInvoiceDateTo.Text.Trim(), "dd/MM/yyyy", null).AddDays(1);

}

if (TxtInvoiceDateTo.Text.Trim() != "")
{
  InvoiceDateTo = Convert.ToDateTime(TxtInvoiceDateTo.Text);
}
if (InvoiceDateTo < InvoiceDateFrom)
    MessageBox.Show("Please select a valid date range.");
 DateTime x = DateTime.Parse("12/8/2012");   //as "12/8/2012" is the your specified date
 dateTimePicker1.MaxDate = x; // or you can use it in one line

if you want to prevent the user to choose date greater than today: 如果要防止用户选择大于今天的日期:

dateTimePicker1.MaxDate = DateTime.Today;

Please see if this is of help! 请查看是否有帮助! C# way of doing is fine. C#的工作方式很好。 But i would rather suggest javascript. 但我宁愿建议使用javascript。

DateTime toDate=DateTime.ParseExact(todateString,"dd/MM/yy",System.Globalization.InvariantCulture);
DateTime fromDate=DateTime.ParseExact(fromdateString,"dd/MM/yy",System.Globalization.InvariantCulture);

int comparison=DateTime.Compare(toDate,fromDate);

if(comparison>=0)
{
     //Post custom error message.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM