开发者

Control user input to textfields

Looking for a way to control user input in text fields. i.e. one field can be double, one field s开发者_JS百科tring, 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, i.e. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜