简体   繁体   English

数据绑定Winforms文本框

[英]Databinding Winforms Textbox

In a nutshell, this databinding works correctly 简而言之,这种数据绑定正常工作

tbTotalTaxDue.DataBindings.Add("Text", I, "TotalTaxDue");

Namely, when I enter an invalid value—like an empty string—then tab out of the TB, the value therein just reverts to the previous value. 也就是说,当我输入一个无效值 - 就像空字符串 - 然后选项卡中的TB一样,其中的值只是恢复到之前的值。 This makes sense since the value entered won't go into the object property of type decimal. 这是有道理的,因为输入的值不会进入decimal类型的object属性。 Unfortunately though, either of these databindings: 不幸的是,这些数据绑定中的任何一个:

tbTotalTaxDue.DataBindings.Add("Text", I, "TotalTaxDue", true, DataSourceUpdateMode.OnPropertyChanged, 0, "C");
tbTotalTaxDue.DataBindings.Add("Text", I, "TotalTaxDue", true, DataSourceUpdateMode.OnValidation, 0, "C");

Behave differently in that when the user enters an empty string, the input will not let the user tab out of the Text Box. 行为方式不同,当用户输入空字符串时,输入将不会让用户选项卡退出文本框。 Is there any way to get the databinding to display as a currency, but simply cancel any invalid edits? 有没有办法让数据绑定显示为货币,但只是取消任何无效的编辑?

You have a couple options: 你有几个选择:

  1. Subclass TextBox and override the OnValidating event. 子类TextBox并覆盖OnValidating事件。 If Text is empty, exit before calling MyBase.OnValidating() to suppress the event. 如果Text为空,请在调用MyBase.OnValidating()之前退出以禁止该事件。

  2. Set CausesValidation = False on the TextBox , and handle the TextChanged event. TextBox上设置CausesValidation = False ,并处理TextChanged事件。 If Text is not empty, manually validate it. 如果Text不为空,请手动验证它。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM