使用正则表达式错误时从文本框中删除最后插入的承租人

remove last inserted charterer from textbox while using regex bug

我正在使用正则表达式将输入内容仅保存到文本框中 并尝试删除任何插入的非数字

private void txtNex_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(txtNex.Text, "[^0-9]"))
    {
        MessageBox.Show("insert numbers only");
        if (txtNex.Text.Length > 1)
        {
            txtNex.Text = txtNex.Text.Substring(0, txtNex.Text.Length - 1);
        }
        else
        {
            txtNexFixPhone.Text = "0";
        }
    }
}

问题是虽然它确实有效,但存在某种错误(或我自己缺乏知识)将输入移到开头,如果我输入另一个非数字,它将产生一个循环,删除所有文本

假设我输入

123a

它会给我错误消息框并删除 "a" 现在,如果我尝试输入另一个 "a",它将出现在 123

之前
a123

以将删除所有输入的错误循环结束

最好验证复选框的值而不是不允许输入某些内容。你可以这样做

decimal number = 0;

if(!decimal.TryParse(txtNex.Text, number))
{
    //Error message
}

如果输入if block,文本框中的文本无法解析为十进制值。您可以制作自定义验证方法,当您需要使用文本框值时,您将在每个地方调用该方法。

编辑:

看来你不喜欢我的回答。这是将清除 not numbers

的代码
   private void txtNex_TextChanged(object sender, EventArgs e)
   {
        string text = txtNex.Text;
        string loopText = txtNex.Text;

        foreach (Char c in loopText)
        {
            string s1 = c.ToString();
            if(Regex.IsMatch(s1, "[^0-9]"))
            {
                if (text.Contains(s1))
                    text = text.Replace(s1, "");
            }
        }

        txtNex.Text = text;
   }

这可能会起作用:

MessageBox.Show("insert numbers only");
if (txtNex.Text.Length > 1)
{
     Regex rgx = new Regex("([^0-9]*)");
     txtNex.Text = rgx.Replace(txtNex.Text, "");
}

一方面,这种方法是个坏主意,因为你检查 TextChanged 上的输入已经太晚了——无效字符在那里,你现在必须删除它——最好这样做在 KeyPress 上并完全阻止输入,以便您根本不必操作文本:

示例:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar))
    {
        MessageBox.Show("insert numbers only");
        e.Handled = true;
    }
}

但是,如果您想要修复将输入移到开头的 bug 并保留当前的解决方案,您需要在操作文本后将光标放在末尾,因为将新文本设置到文本框会重置光标的位置。

示例:

// Manipulate the text:
txtNex.Text = txtNex.Text.Substring(0, txtNex.Text.Length - 1);

// Put the cursor at the end:
txtNex.Select(txtNex.Text.Length, 0);