删除文本框中所有非数字

本文关键字:数字 文本 删除 | 更新日期: 2023-09-27 18:15:25

我有一个输入数字的textbox1。例子:123我也有textbox2的总和显示。示例:6 (1+2+3)

我需要的是。如果只有数字在我的textbox1,那么一切都很好,我得到sum。如果有更多的数字像1a2b3c我想要的程序显示警告和文本消息框。删除所有非数字?如果这个人按下Yes,那么它会删除abc,只剩下123。如果没有,则显示Error。

我的代码:
 private void button1_Click(object sender, EventArgs e)
    {
        int cipari = Convert.ToInt32(textBox1.Text);
        int summa = 0;
        for (int n = cipari; n > 0; summa += n % 10, n /= 10) ;
        DialogResult dialogResult = MessageBox.Show("Delete all non-digits?", "Warning", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            textBox2.Text = summa.ToString();
        }
        else if (dialogResult == DialogResult.No)
        {
            textBox2.Text = "Error! You can't sum non-digits!";
        }

    }

删除文本框中所有非数字

检查是否存在非数字字符:

foreach(Char c in textBox1.Text) {
    if( !Char.IsDigit( c ) ) {
        MessageBox.Show("Non-digits detected");
        return;
    }
}

如果你只想要数字,那么你可以使用一个小函数的擦洗和警告用户对每个受影响的文本框的textchanged事件。这将向用户显示一个警告,然后删除无效字符。

private void validateText(TextBox tb)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(tb.Text, @"[^0-9]"))
            {
                MessageBox.Show("Please enter only numbers.");
                tb.Text = tb.Text.Remove(tb.Text.Length - 1);
                tb.Refresh();
                tb.SelectionStart = tb.Text.Length;
                tb.SelectionLength = 0;
            }
        }

使用:

private void textbox1_TextChanged(object sender, EventArgs e)
        {
            validateText(textbox1);
        }

老实说,这是一个奇怪的程序流程。但是你可以这样做:

if(!textBox2.Text.All(char.IsDigit)
{
    DialogResult dialogResult = MessageBox.Show("Delete all non-digits?", "Warning", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
        textBox2.Text = string.Concat(textBox2.Text.Where(char.IsDigit));
    }
    else if (dialogResult == DialogResult.No)
    {
        textBox2.Text = "Error! You can't sum non-digits!";
    }
}

为什么每次用户输入字母时都要删除数字,我想最好的做法是永远不要让用户输入除数字以外的任何东西。

首先创建一个函数,检查输入的文本是否是整数像这样:

private bool IsNumber(string text)
    {
        Regex regex = new Regex("[^0-9.-]+"); //regex that matches if the text contains only numbers
        return regex.IsMatch(text);
    }

然后使用文本框的PreviewTextInput事件来阻止用户输入整数(小数和-)。

private void Button_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = IsNumber(e.Text);
    }

将e.handled设置为IsNumber函数是很重要的,因为这里只有它使用这个方法检查输入字符串是否可接受,并阻止用户输入它。