代码之家  ›  专栏  ›  技术社区  ›  eomeroff

Win窗体文本框掩码

  •  6
  • eomeroff  · 技术社区  · 15 年前

    如何在Win窗体文本框上放置掩码,使其仅允许数字? 以及它对另一个蒙版数据、电话拉链等的工作原理。

    我正在使用Visual Studio 2008 C#

    谢谢。

    6 回复  |  直到 8 年前
        1
  •  3
  •   Mark Byers    15 年前

    是否要阻止不允许的输入,或在可以继续之前验证输入?

    前者可以在用户按下按键时混淆用户,但不会发生任何事情。通常最好显示按键,但显示输入当前无效的警告。例如,为屏蔽电子邮件地址正则表达式而设置可能也相当复杂。

    ErrorProvider 允许用户键入所需内容,但在键入时显示警告。

    对于只允许数字的文本框的第一个建议,您可能还需要考虑 NumericUpDown .

        2
  •  5
  •   Brett Allen    15 年前
        3
  •  1
  •   Jason Sturges    12 年前
        4
  •  0
  •   pfeds    12 年前

    如上所述,使用 MaskedTextBox .

    它也值得使用 ErrorProvider .

        5
  •  0
  •   RekhaShanmugam    10 年前

    使用Mask文本框并分配MaskTextBoxID.Mask。

    如果要使用文本框,则必须为其编写正则表达式

        6
  •  0
  •   Ashraf Sada    8 年前

    控制用户的按键事件,通过不允许任何不需要的字符来屏蔽输入。

    只允许带小数的数字:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // allows 0-9, backspace, and decimal
            if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
            {
                e.Handled = true;
                return;
            }
    
            // checks to make sure only 1 decimal is allowed
            if (e.KeyChar == 46)
            {
                if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
                    e.Handled = true;
            }
        }
    

    仅允许电话号码值:

    private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
         if (e.KeyChar == '+' || e.KeyChar == '-') return;
         if (e.KeyChar == 8) return;
         e.Handled = true;
    
    }