Only allow specific characters in textbox

后端 未结 6 898
走了就别回头了
走了就别回头了 2020-12-01 21:17

How can I only allow certain characters in a Visual C# textbox? Users should be able to input the following characters into a text box, and everything else should be blocked

6条回答
  •  难免孤独
    2020-12-01 21:23

    As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus

    The below regex lets you match those characters you want to allow

    Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
    MatchCollection matches = regex.Matches(textValue);
    

    and this does the opposite and catches characters that aren't allowed

    Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
    MatchCollection matches = regex.Matches(textValue);
    

    I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged

    textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
        MatchCollection matches = regex.Matches(textBox1.Text);
        if (matches.Count > 0) {
           //tell the user
        }
    }
    

    and to validate single key presses

    textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        // Check for a naughty character in the KeyDown event.
        if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
        {
            // Stop the character from being entered into the control since it is illegal.
            e.Handled = true;
        }
    }
    

提交回复
热议问题