2011-01-07 34 views
4

我遇到与this post相同的问题。它导致我的数据集对象的数值可为空值。当这个对象的属性初始值为null时,我可以退出我的文本框。当我的文本框有一个初始数值并清除文本框时,我无法退出。数据绑定文本框无法退出

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

任何想法或建议吗?提前谢谢了!

+0

可能重复的[数据绑定文本框:不能退出](http://stackoverflow.com/questions/217912/data-bound-textbox-cant-exit) – 2011-01-07 16:54:00

+0

人们已经投票决定将其作为您链接的问题的完全重复。你能解释你的问题是如何不同的,以及为什么其他问题的答案*不适用于你的情况? – 2011-01-07 17:02:53

回答

4

(对不起,起初我没有看到你的回复要求比手动附加格式/分析事件更简单的方法,所以我的答案可能不够满足,但对于其他人有同样的问题,代码片段可能很有用)。

您可以使用该文本框的绑定的格式和分析事件将空字符串转换为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