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

时间:2012-11-28 16:27:48

标签: c# asp.net date

我根据字段中的两个日期和Asp.net中的To字段搜索数据

我想阻止用户输入大于日期的发件人日期并向用户显示消息请选择有效的日期范围

  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);
}

3 个答案:

答案 0 :(得分:2)

if (InvoiceDateTo < InvoiceDateFrom)
    MessageBox.Show("Please select a valid date range.");

答案 1 :(得分:1)

 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

如果您想阻止用户选择比今天更大的日期:

dateTimePicker1.MaxDate = DateTime.Today;

答案 2 :(得分:0)

请查看这是否有帮助! C#的做法很好。但我宁愿建议使用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.
}