绑定可空的DateTime到MaskedTextBox中 [英] Bind nullable DateTime to MaskedTextBox

查看:174
本文介绍了绑定可空的DateTime到MaskedTextBox中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须绑定到一个nullabe日期时间屏蔽的文本框,但是当日期为空白,在蒙面文本框中验证将无法完成。有没有办法迫使这种行为?我想为空白文本框等于空日期时间。

I have a masked text box bound to a nullabe datetime, but when the date is blanked out, the validation on the masked text box won't complete. Is there a way to force this behaviour? I want a blanked out text box to equal a null DateTime.

在文本框已经是空,验证工作。它仅当有一个日期已绑定打破我尝试空白吧。

When the textbox is already null, the validation works. It only breaks when there is a date already bound and I try to blank it out.

推荐答案

我想通了,它没有有验证来做。这是当日期正在解析回日期时间。

I figured out it didn't have to do with the validation. It was when the date was being parsed back to the datetime.

这可能不是最优雅的方式来做到这一点,但它确实工作。如果有人知道一个更好的办法,请让我知道。

This may not be the most elegant way to do this, but it does work. If anyone knows a better way, please let me know.

我现在有这个代码。

public static void FormatDate(MaskedTextBox c) {
    c.DataBindings[0].Format += new ConvertEventHandler(Date_Format);
    c.DataBindings[0].Parse += new ConvertEventHandler(Date_Parse);
}

private static void Date_Format(object sender, ConvertEventArgs e) {
    if (e.Value == null)
        e.Value = "";
    else
        e.Value = ((DateTime)e.Value).ToString("MM/dd/yyyy");
}

static void Date_Parse(object sender, ConvertEventArgs e) {
    if (e.Value.ToString() == "  /  /")
        e.Value = null;
}

这篇关于绑定可空的DateTime到MaskedTextBox中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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