问题描述
我有一个文本框,带有文本属性绑定到数据集列的datatype设置为system.dateTime.
结合上的格式设置为 dd-mm-yyyy .
当用户输入日期时,它试图将其转换为日期,但可能会在看似无效的日期中提出一些奇怪的值.
例如:
textBox1.Text = "01-02-200";
应该是无效的日期,但格式为 01-02-0200 .
是否有一种简单的方法可以通过设置有效范围或在绑定/文本框上覆盖事件?
推荐答案
a .NET DateTime在01/01/0001至31/12/9999 23:59:59.9999999中,因此2001/01/200被认为是有效的.
您可以验证输入并限制范围:验证事件将是进行验证的地方.您需要将字符串解析为日期时间并验证其范围.
允许的范围将取决于应用程序.例如,以下代码将DateTime限制为可以存储在SQL Server 2005 DateTime列(01-01-1753至31-12-999)中的值:
private void textBox1_Validating(object sender, CancelEventArgs e) { DateTime date; if (!DateTime.TryParseExact(textBox1.Text, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { MessageBox.Show(textBox1.Text + " is not a valid date"); textBox1.Focus(); e.Cancel = true; return; } if ((date < (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) || (date > (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue)) { MessageBox.Show(textBox1.Text + " is out of range"); textBox1.Focus(); e.Cancel = true; return; } }
其他推荐答案
有没有理由不使用日期选择器控件而不是文本框?将解决验证问题,并可能使用户成为更好的体验.
问题描述
I have a textbox with the Text property bound to a dataset column with the DataType set to System.DateTime.
The FormatString on the Binding is set to dd-MM-yyyy.
When the user enters a date it attempts to convert it to a date but can come up with some strange values for a seemingly invalid date.
For example:
textBox1.Text = "01-02-200";
Should be an invalid date but it formats it as 01-02-0200.
Is there an easy way to catch these out-of-bounds values either through setting a valid range or overriding an event on the binding/textbox?
推荐答案
A .NET DateTime is in the range 01/01/0001 to 31/12/9999 23:59:59.9999999, so 01/01/200 is considered to be valid.
You can validate the input and restrict the range: the Validating event would be the place to do your validation. You'll need to parse the string into a DateTime and validate its range.
The allowed range will be application dependent. For example, the following code will restrict the datetime to values that can be stored in a SQL Server 2005 DATETIME column (01-01-1753 to 31-12-999):
private void textBox1_Validating(object sender, CancelEventArgs e) { DateTime date; if (!DateTime.TryParseExact(textBox1.Text, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { MessageBox.Show(textBox1.Text + " is not a valid date"); textBox1.Focus(); e.Cancel = true; return; } if ((date < (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) || (date > (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue)) { MessageBox.Show(textBox1.Text + " is out of range"); textBox1.Focus(); e.Cancel = true; return; } }
其他推荐答案
Any reason not to use a date picker control instead of a textbox? Would solve validation problem and probably make it a better experience for the user.