Reputation: 38333
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?
Upvotes: 0
Views: 3453
Reputation: 124696
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;
}
}
Upvotes: 2
Reputation: 20674
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.
Upvotes: 0