如何在 C# windows 窗体的文本框中接受日期格式的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18160349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to accept value in date format in textbox in C# windows form?
提问by Ruchi Desai
I have a Field in my windows form that asks user to enter their Birth Date... How do i validate my form to accept only numbers and "/"( separator Symbol ) and also in dd/mm/yyyy format.. Also day should be less than 31, Month should be less than 12 and Year not greater than 2012
我的 Windows 表单中有一个字段,要求用户输入他们的出生日期...我如何验证我的表单以仅接受数字和“/”(分隔符符号)以及 dd/mm/yyyy 格式..也是一天应小于 31,月应小于 12,年份不大于 2012
回答by peter
Do you want to do the validation after the user is done? In that case you could just try to parse the string as a date and see if it is a correct date. In that case you also get the days in month right.
是否要在用户完成后进行验证?在这种情况下,您可以尝试将字符串解析为日期,看看它是否是正确的日期。在这种情况下,您也可以正确获取月份中的天数。
回答by Ehsan
Textbox is not the control to accept datetime input. There is a built in control DateTimePicker
that should be used instead. The problem with your approach is that even if you do masking of textbox for one format like dd/mm/yyyy
user may want to enter in mm/dd/yyyy
. So, quite a lot of error handling. Whereas you need not worry about any such thing in case of datetimepicker
.
文本框不是接受日期时间输入的控件。有一个DateTimePicker
应该使用的内置控件。您的方法的问题在于,即使您为一种格式(如dd/mm/yyyy
用户可能想要输入mm/dd/yyyy
. 所以,相当多的错误处理。而在datetimepicker
.
Even then if you want to go with textbox. Do this,
即便如此,如果您想使用文本框。做这个,
DateTime dt;
if (DateTime.TryParseExact(yourTexbox.Text.Trim(), "yourformattoaccept", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//your code if parsing is successful
}
回答by rene
You make your life easier if you use the datatimepicker but if you still feel you want to present a textbox and help the user to prevent entering an illegal date this sample code will get you going. I surpress keys and validate the textentry on exit of the field and prevent leaving if there is no valid date.
如果您使用 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));
}
回答by King King
I think you should go for DateTimePicker
, however we can also use a TextBox
with some Validating
. There are many kinds of validating data. We can prevent user from typing invalid data or we can also check the data after user submitting. Here I'll introduce you the second approach because the first requires more code to do, it may prevent user from typing invalid data but it also has to prevent user from pastinginvalid data. That's why the first approach needs more code.
我认为你应该去DateTimePicker
,但是我们也可以使用TextBox
一些Validating
。验证数据有很多种。我们可以防止用户输入无效数据,也可以在用户提交后检查数据。在这里我将向您介绍第二种方法,因为第一种方法需要更多的代码来完成,它可以防止用户输入无效数据,但它也必须防止用户粘贴无效数据。这就是为什么第一种方法需要更多代码的原因。
For the second approach you can add code to a Validating
event handler for your TextBox
and use a little Regex
like this:
对于第二种方法,您可以Validating
为您的事件处理程序添加代码TextBox
并使用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;
}
}
You can add some Submit
button to your form together with your textBox1
to test. I hope you know how to register the Validating
event handler for your textBox1
.
您可以将一些Submit
按钮添加到您的表单中以textBox1
进行测试。我希望你知道如何Validating
为你的textBox1
.