简体   繁体   English

C#中的动态文本框验证

[英]dynamic textbox validation in C#

my text box takes only numeric values,from 0 to 255 (1 byte),how can i prevent the user entering the number>255...the moment the 3rd digit is entered it should validate.right now my code validating when you come out of textbox and showing message.Any help greatly appreciated. 我的文本框仅接受从0到255(1字节)的数值,我如何防止用户输入数字> 255 ...输入第三个数字后,它应该通过验证。超出文本框并显示消息。非常感谢您的帮助。

  private void cor_o_gain_Validating(object sender, CancelEventArgs e)
    {
        try
        {
            int entered = int.Parse(cor_o_gain.Text);
            if (entered > 255)
            {
                e.Cancel = true;
                MessageBox.Show("Enter the number between 0 and 255");
            }
        }
        catch (FormatException)
        {
          //  e.Cancel = true;
        }
    } 

You might consider not doing this because it's annoying. 您可能会考虑这样做,因为这很烦人。 If a user types "30" and changes his mind while the cursor is before the 3, he might type "40" and then hit delete twice. 如果用户键入“ 30”并在光标位于3之前时改变了主意,则可以键入“ 40”,然后按两次Delete键。 Your app would beep at him and show a messagebox. 您的应用会向他发出蜂鸣声,并显示一个消息框。

If you must validate while he's typing, consider putting a label next to his text and updating it to read "Invalid input" or some such. 如果您必须在输入文字时进行验证,请考虑在文字旁边放置一个标签,然后将其更新为“无效输入”或类似内容。 Do it on keypress, keyup or keydown as mentioned elsewhere. 如其他地方提到的那样,在按键,按键或按下按键时进行操作。

Check out for the key events; 查看主要事件; keypress, keydown, keyup etc. 按键,按键,按键等

You should use a numericUpDown control instead, and set the min and max values to be within 0 and 255. 您应该改用numericUpDown控件,并将最小值和最大值设置为0到255之间。

System.Windows.Forms.NumericUpDown n = new System.Windows.Forms.NumericUpDown();
n.Minimum = 0;
n.Maximum = 255;

I would say reconsider your implementation. 我会说重新考虑您的实施。 I have used software designed like that and it is very annoying. 我使用过这样设计的软件,这很烦人。 It likely going to piss your users off over time and provide no real benefit. 随着时间的流逝,它很可能会激怒您的用户,并且没有真正的好处。

Still if you absolutely MUST stop the user in the middle of typing (once again question if you SHOULD) then you need a "faster acting" event like Keypress. 仍然,如果您绝对必须在键入过程中停止用户(再次询问您是否应该),那么您需要一个诸如Keypress之类的“动作更快”的事件。

There are lots of "gentler" implementations though. 虽然有很多“温特勒”实现。 One option (not the only one) would be to change background color of textbox and make an error message visible to alert but not block the user that the input is invalid. 一种选择(不是唯一的一种选择)是更改文本框的背景颜色并使可见的错误消息发出警报,但不会阻止用户输入无效。 This allows user to change the text without being interrupted (by the message box) while trying to change the text. 这允许用户在尝试更改文本时更改文本而不会被消息框打断(不被消息框打断)。

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

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