简体   繁体   中英

Control user input to textfields

Looking for a way to control user input in text fields. ie one field can be double, one field string, one field int. Is there a library I can use to look after this for me?

Using: Vs 2008, C#, WPF

int.TryParse()

Much easier!!

You can try using regex on the textboxes to constrain/validate user input...

http://msdn.microsoft.com/en-us/library/ms998267.aspx

One can use the textbox's Validate event to set up a validation delegate that ensures the box has valid text:

textbox1.Validate += delegate(sender, eventArguments)
                     {
                         double val;
                         if (!int.TryParse(textbox1.Text, out val)
                         {
                             eventArguments.Cancel = true;
                         }
                     }

However, the Validate event is not raised until the control in question loses focus, which may not provide the user-experience you require, ie the user will be able to type an invalid value and it will not be until they attempt to leave the control that the text will be validated. If you actually want to prevent invalid characters or values from being typed, you may need to intercept the TextChanged event and validate the text at each step.

If you do choose to react to TextChanged, then be aware that intermediate values may not parse to the required type — for example if the textbox is constrained to a date, and the user is attempting to enter '26/11/2009', then the text will be '2' after the first character which is not a valid date.

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