【问题标题】:how to accept value in date format in textbox in C# windows form?如何在 C# windows 窗体的文本框中接受日期格式的值?
【发布时间】:2013-08-10 18:02:25
【问题描述】:

我的 Windows 窗体中有一个字段,要求用户输入他们的出生日期... 我如何验证我的表格只接受数字和“/”(分隔符)以及 dd/mm/yyyy 格式.. 天数应小于 31,月数应小于 12,年数不得大于 2012

【问题讨论】:

  • 改用日期时间选择器
  • 您应该改用 DateTimePicker 控件。
  • 更好地使用日期时间控件。如果您只想使用文本框,请为您自己设计一个用户控件。
  • 这个问题绝对有效。各位投票者,你认为如果 Ruchi Desai 知道 DateTimePicker,他会问这个吗?如果您搜索如何验证日期字段或某些日期输入,答案也非常有用。因为像你这样的用户,StackOverflow 很烂。
  • DateTimePicker不能为空,但有时需要日期输入控件为空;此外,如果您知道确切的日期,将其作为文本输入通常比在(繁琐的)日历中选择日期更快。因此这个问题是绝对合法的。

标签: c# winforms


【解决方案1】:

文本框不是接受日期时间输入的控件。应该使用一个内置控件DateTimePicker。您的方法的问题在于,即使您为dd/mm/yyyy 之类的一种格式屏蔽了文本框,用户也可能希望输入mm/dd/yyyy。所以,相当多的错误处理。而对于datetimepicker,您无需担心任何此类事情。

即使你想使用文本框。这样做,

DateTime dt;
if (DateTime.TryParseExact(yourTexbox.Text.Trim(), "yourformattoaccept", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
   //your code if parsing is successful
}

【讨论】:

    【解决方案2】:

    我认为您应该选择DateTimePicker,但我们也可以使用TextBox 和一些Validating。有多种验证数据。我们可以防止用户输入无效数据,也可以在用户提交后检查数据。这里我将向您介绍第二种方法,因为第一种方法需要更多的代码来完成,它可能会阻止用户输入无效数据,但它也必须防止用户粘贴无效数据。这就是为什么第一种方法需要更多代码的原因。

    对于第二种方法,您可以将代码添加到 TextBoxValidating 事件处理程序,并像这样使用一点 Regex

    private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            Regex reg = new Regex(@"^(\d{1,2})/(\d{1,2})/(\d{4})$");
            Match m = reg.Match(textBox1.Text);
            if (m.Success)
            {
                int dd = int.Parse(m.Groups[1].Value);
                int mm = int.Parse(m.Groups[2].Value);
                int yyyy = int.Parse(m.Groups[3].Value);
                e.Cancel = dd < 1 || dd > 31 || mm < 1 || mm > 12 || yyyy > 2012;                
            }
            else e.Cancel = true;
            if (e.Cancel)
            {
                if (MessageBox.Show("Wrong date format. The correct format is dd/mm/yyyy\n+ dd should be between 1 and 31.\n+ mm should be between 1 and 12.\n+ yyyy should be before 2013", "Invalid date", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                    e.Cancel = false;
            }
        }
    

    您可以将一些Submit 按钮与textBox1 一起添加到您的表单中以进行测试。我希望您知道如何为您的textBox1 注册Validating 事件处理程序。

    【讨论】:

      【解决方案3】:

      如果您使用 datatimepicker 会让您的生活更轻松,但如果您仍然想呈现一个文本框并帮助用户防止输入非法日期,那么此示例代码将助您一臂之力。 我按下键并在字段退出时验证文本输入,如果没有有效日期,则防止离开。

      private void textBox1_Validating(object sender, CancelEventArgs e)
      {
          TextBox tb = sender as TextBox;
          if (tb != null)
          {
              DateTime res;
              e.Cancel = !DateTime.TryParse(tb.Text, out res);
              if (e.Cancel)
              {
                 // if you have an errorProvider...
                 this.errorProvider1.SetError(
                       tb, 
                       String.Format("'{0}' is not a valid date", tb.Text));
              }
          }
      }
      
      private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
      {
          // add extra checks to determine if
          // this char is allowed, set Handled to 
          // false. If you want to surpress the key
          // set it to true
          // get the current separator or have your own, then simply say @"/"
          var dateSep = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
          e.Handled = !(Char.IsDigit(e.KeyChar) ||
                      (dateSep.IndexOf(e.KeyChar)>-1) ||
                      Char.IsControl(e.KeyChar));    
      }
      

      【讨论】:

        【解决方案4】:

        您想在用户完成后进行验证吗?在这种情况下,您可以尝试将字符串解析为日期并查看它是否是正确的日期。在这种情况下,您还可以获得正确的月份日期。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-23
          • 1970-01-01
          • 1970-01-01
          • 2016-08-07
          • 2011-03-08
          • 2018-10-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多