如何验证文本条目以仅包含数字?

时间:2013-01-13 13:52:06

标签: c# .net

我想强制使用我的程序的人只输入c#中文本标签中的数字。我怎样才能做到这一点? 例如: 方程数:(他应该只输入一个数字)

此代码要求他在210之间输入一个数字,但我需要一个字母代码

if (int.Parse(txt1.Text) < 2 || int.Parse(txt1.Text) > 10)
   {
     l6.ForeColor = System.Drawing.Color.Red;
     l6.Text = "Svp choisir un nombre entre 2 et 10 ... Soyez Logique!";
   }

4 个答案:

答案 0 :(得分:1)

在文本框按键事件中放置此(或根据您想让用户输入的内容的变体),所以基本上您将在此文本框中管理按键操作。 添加System.Media库以在用户输入错误密钥时使用蜂鸣声,或将其从代码中删除...

        if ((e.KeyChar >= '0') && (e.KeyChar <= '9') && (txt1.Text.Length < 10))
        {

        }
        else if (e.KeyChar == 0x08)
        {
            //BACKSPACE CHAR
        }
        else if (txt1.SelectionLength > 0)
        {
            //IF TEXT SELECTED -> LET IT OVERRIDE
        }
        else
        {
            e.Handled = true;
            SystemSounds.Beep.Play();
        }

答案 1 :(得分:0)

你使用什么GUI? 使用Winforms有两种方式可以想到:

  1. 我建议:使用numericUpDown Control而不是textBox。这样,用户只能输入数字并具有漂亮的向上/向下箭头来更改值。另外,您可以处理光标键。

  2. 实施Validating事件处理程序。

答案 2 :(得分:0)

if (txt1.Text.Trim().Length > 0)
{
    // Parse the value only once as it can be quite performance expensive.
    Int32 value = Int32.Parse(txt1.Text)

    if ((value >= 2) && (value <= 10))
    {
        l6.ForeColor = Color.Red;
        l6.Text = "Svp choisir un nombre entre 2 et 10 ... Soyez Logique!";

        // Clear the text...
        txt1.Text = "";
    }
    else
    {
        // Your code here...
    }
}

但是,恕我直言,TryParse更好,因为它可以更好地处理错误的字符串格式:

if (txt1.Text.Trim().Length > 0)
{
    Int32 value;

    if (!Int32.TryParse(txt1.Text, out value))
    {
        l6.ForeColor = Color.Red;
        l6.Text = "Svp choisir un nombre entre 2 et 10 ... Soyez Logique!";

        // Clear the text...
        txt1.Text = "";
    }
    else
    {
        // Your code here...
    }
}

答案 3 :(得分:0)

检查在文本框中插入文本以避免非数字字符的各种方法并不是一件容易的事,而且往往会在某处失败。例如,从剪贴板粘贴的文本呢?,退格键,删除键,左键,右箭头键怎么办?

在我看来,最好采用不同的方法 使用Validating事件,让用户键入或粘贴他想要的任何内容。在验证事件中,您是否检查并建议用户或添加特殊的errorProvider来发出错误信号:

    private void l6_Validating(object sender, CancelEventArgs e)
    {
        int isNumber = 0;
        if (l6.Text.Trim().Length > 0)
        {
            if (!int.TryParse(l6.Text, out isNumber))
            {
                e.Cancel = true;
                errorProvider1.SetError(l6, "Svp choisir un nombre entre 2 et 10 ...";);
            }
            else
            {
                errorProvider1.SetError(l6, "");
            }
        }
    }
}