C# - 文本框验证

7

我有一些代码,用于检查并确保用户在字段中输入的是1到10之间的整数。

但是,如果用户将焦点移出该字段,则“错误”的数据(例如“fdgfdg”)仍然留在该字段中。因此,有人可以演示一下,当焦点离开该字段时,如果数据无效,则会输入默认值,例如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");
            }
        }

1
@Gats:这是一个WinForms桌面应用程序... - Peter Kelly
这是WinForms而不是网页。 - user744186
1
@Gats:即使是Web应用程序,服务器端验证也是必需的。客户端验证应该是服务器端验证的方便补充。 - František Žiačik
1
你还应该看一下ErrorProvider,它是一个方便的方式来告诉用户输入有误。 - Zeus
我只是一个工具。这就是在凌晨4点回答问题时会发生的事情 :) - Gats
4个回答

15

你可以在这里使用几个事件:LeaveLostFocusValidating。关于这些不同事件的更多讨论可以在MSDN 这里找到

在某些情况下,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();
        }
    }

0

0
如果您正在手动编写验证,就像您在此处所做的那样,那么您只需要在 MessageBox.Show() 之后设置默认值即可。
在标准WinForms中,我认为您没有任何框架支持验证,但您可以查看此链接 http://msdn.microsoft.com/en-us/library/ms951078.aspx 以获取灵感,这样您就不会在应用程序中散布这种逻辑。

0
使用文本框控件上的Leave事件进行验证并设置默认值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接