.net - 数据绑定(bind)文本框无法退出

标签 .net winforms data-binding textbox

我和 this post 有同样的问题.它是由我的数据集对象的数字可为空值引起的。当这个对象的属性的初始值为 null 时,我可以退出我的文本框。当我的文本框有一个初始数值并清除文本框时,我无法退出。

我希望能够通过清除文本框来提供空值。我知道这是一个验证问题,当将“CausesValidating”属性设置为 false 时,我可以退出。我的属性设置功能也永远无法达到。

有什么想法或建议吗?提前谢谢了!

最佳答案

(抱歉,起初我没有看到您的回复要求比手动附加到 Format/Parse 事件更简单的方法,所以我的回答可能不够令人满意,但对于遇到同样问题的其他人来说,代码片段可能很有用.)

您可以使用该 TextBox 的 Binding 的 Format 和 Parse 事件将空字符串转换为 DBNull.Value 并返回,以便控件有效并且您可以离开它。

// Call AllowEmptyValueForTextbox() for each TextBox during initialization.

void AllowEmptyValueForTextBox(TextBox textBox)
{
    if (textBox.DataBindings["Text"] != null)
    {
        textBox.DataBindings["Text"].Format += OnTextBoxBindingFormat;
        textBox.DataBindings["Text"].Parse += OnTextBoxBindingParse;
    }
}

void OnTextBoxBindingParse(object sender, ConvertEventArgs e)
{
    // Convert the value from the textbox to a value in the dataset.
    string value = Convert.ToString(e.Value);
    if (String.IsNullOrEmpty(value))
    {
        e.Value = DBNull.Value;
    }
}

void OnTextBoxBindingFormat(object sender, ConvertEventArgs e)
{
    // Convert the value from the dataset to a value in the textbox.
    if (e.Value == DBNull.Value)
    {
        e.Value = String.Empty;
    }
}

当数据集中的字段为空时,您可以使用相同的机制用“(未设置)”之类的字符串填充文本框,而不是向用户显示一个空的文本框。在 Format 方法中将 DBNull.Value 转换为“(未设置)”,并在 Parse 方法中将其转换回来。

也可以看看:
http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.parse

关于.net - 数据绑定(bind)文本框无法退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4628029/

相关文章:

c# - 自定义 JSON.Net 输出

c# - 如何测试Ctrl键向上?

c# - 从后台线程更新绑定(bind)属性

asp.net - 错误 : "Fill: SelectCommand.Connection property has not been initialized."

c# - 在另一个列表中的列表中查找项目?

c# - 数据 View 和数据表有什么区别?

c# - Microsoft Sync Framework - 双向同步如何工作?

c# - 从 C# Windows 应用程序读取/写入三星安卓手机/平板电脑

c# - 将系统默认上下文菜单添加到无边框 Windows 窗体

c# - 嵌套 INotifyPropertyChanged 类不起作用