Prevent numbers from being pasted in textbox in .net windows forms

前端 未结 3 1537
鱼传尺愫
鱼传尺愫 2021-01-16 04:01

I have prevented numbers from being typed in text box using key down event. But when using Ctrl+V or pasting content through mouse, the numbers are being entered in the text

3条回答
  •  悲&欢浪女
    2021-01-16 04:51

    On quite simple approach would be to check the text using the TextChanged event. If the text is valid, store a copy of it in a string variable. If it is not valid, show a message and then restore the text from the variable:

    string _latestValidText = string.Empty;
    private void TextBox_TextChanged(object sender, EventArgs e)
    {
        TextBox target = sender as TextBox;
        if (ContainsNumber(target.Text))
        {
            // display alert and reset text
            MessageBox.Show("The text may not contain any numbers.");
            target.Text = _latestValidText;
        }
        else
        {
            _latestValidText = target.Text;
        }
    }
    private static bool ContainsNumber(string input)
    {
        return Regex.IsMatch(input, @"\d+");
    }
    

    This will handle any occurrence of numbers in the text, regardless of where or how many times they may appear.

提交回复
热议问题