数据绑定格式化为DateTime列 [英] Data binding formatting to a DateTime column

查看:130
本文介绍了数据绑定格式化为DateTime列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,其中 Text 属性绑定到数据集列,DataType设置为System.DateTime。

Binding中的FormatString设置为 dd-MM-yyyy

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.

例如:

textBox1.Text = "01-02-200";

应该是无效的日期,但格式为 01-02-0200

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?

推荐答案

.NET DateTime的范围是01/01/0001到31/12/9999 23:59:59.9999999,所以01 / 01/2008被认为是有效的。

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.

您可以验证输入并限制范围:验证事件将是您进行验证的地方。您需要将字符串解析为DateTime并验证其范围。

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.

允许的范围将取决于应用程序。例如,以下代码将将datetime限制为可存储在SQL Server 2005 DATETIME列(01-01-1753至31-12-999)中的值:

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

这篇关于数据绑定格式化为DateTime列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆