简体   繁体   English

C# - TextBox验证

[英]C# - TextBox Validation

I have some code that checks and makes sure that when the users enters in the field an integer from 1 - 10 has to be input. 我有一些代码检查并确保当用户在字段中输入时必须输入1到10的整数。

Although if the users takes focus of the field, the "bad" data (such as "fdgfdg") is still left in the field. 虽然如果用户关注该字段,那么“坏”数据(例如“fdgfdg”)仍然留在该字段中。 So could some demonstrate how when focus is lost on the field, if the data is not valid, a default value will be entered instead eg 5 因此,有些人可以演示当焦点在场上丢失时,如果数据无效,则输入默认值,例如5

private void textBox4_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int numberEntered = int.Parse(textBox4.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                    MessageBox.Show("You must enter a number between 1 and 10");
                }
            }
            catch (FormatException)
            {

                MessageBox.Show("You need to enter an integer");
            }
        }

There are several events that you can use here, Leave , LostFocus and Validating there is more discussion of these various events on MSDN here . 你可以在这里使用几个事件, LeaveLostFocusValidating这里有关于MSDN上这些不同事件的更多讨论。

Under certain scenarios the Leave and the LostFocus will not fire so the best to use in your case is the Validating event: 在某些情况下, LeaveLostFocus不会触发,因此在您的情况下最好使用的是Validating事件:

    textBox1.Validating += new CancelEventHandler(textBox1_Validating);


    void textBox1_Validating(object sender, CancelEventArgs e)
    {
        int numberEntered;

        if (int.TryParse(textBox1.Text, out numberEntered))
        {
            if  (numberEntered < 1 || numberEntered > 10) 
            { 
                MessageBox.Show("You have to enter a number between 1 and 10");
                textBox1.Text = 5.ToString();
            }
        }
        else
        {
            MessageBox.Show("You need to enter an integer");
            textBox1.Text = 5.ToString();
        }
    }

看看这里 ,我会使用TryParse

if you are hand-rolling validation like you do here, all you need to do is to set the default value after you MessageBox.Show() 如果您像在这里一样进行手动滚动验证,那么您需要做的就是在MessageBox.Show()之后设置默认值

in standard winforms I don't think you have any framework support for validation, but you could look at this: http://msdn.microsoft.com/en-us/library/ms951078.aspx for inspiration so you don't scatter this logic throughout your app 在标准winforms中,我认为你没有任何框架支持验证,但你可以看看这个: http//msdn.microsoft.com/en-us/library/ms951078.aspx的灵感,所以你不要分散整个应用程序的这个逻辑

使用文本框控件上的Leave事件来验证并设置默认值

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

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