如何验证文本输入以仅包含数字

本文关键字:输入 包含 数字 文本 何验证 验证 | 更新日期: 2023-09-27 17:52:33

我想强制使用我的程序的人只在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!";
   }

如何验证文本输入以仅包含数字

将此(或此的变体,根据您想让用户输入的内容)放在文本框keypress事件中,因此基本上您将管理该文本框中的按键。添加系统。媒体库使用蜂鸣声,如果用户输入错误的键,或从代码中删除它…

        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();
        }
 之前

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...
    }
}

您使用什么GUI ?使用Winforms有两种方法:

  1. 我建议:使用数字上下控制而不是文本框。这样,用户只能输入数字,并有很好的向上/向下箭头来改变值。另外你还可以处理光标键

  2. 实现一个验证事件处理程序

检查在文本框中插入文本以避免非数字字符的各种方法并不是一项容易的任务,而且通常在某些地方会失败。例如,从剪贴板粘贴的文本呢?还有退格键、删除键、左键、右键呢?

在我看来,最好遵循不同的方法。
使用validation事件,让用户键入或粘贴他想要的任何内容。在验证事件中,您是否检查并通知用户或添加一个特殊的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, "");
            }
        }
    }
}