简体   繁体   中英

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. This makes sense since the value entered won't go into the object property of type decimal. 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. If Text is empty, exit before calling MyBase.OnValidating() to suppress the event.

  2. Set CausesValidation = False on the TextBox , and handle the TextChanged event. If Text is not empty, manually validate it.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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