Search code examples
c#winformsmaskedtextbox

Input Arithmetic Operators Only in Masked TextBox in C#


I am creating application in windows form in c#

I know that in masked textbox, we can restrict the format of input, and also restrict the which type of input we can validate like numbers only, characters only, alphanumeric. But now I am trying to put restriction on the masked text (or simple textbox) to accept a single arithmetic operator (+ or - or * or /) only. I have searched the web but didn't find a way. Please help me to solve this issue.


Solution

  • I think the easier way would be limit the Max Length characters to 1 in textbox properties

    and in the TextChanged event you can write

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
      if (textBox1.Text.Length > 0)
      {
        char[] SpecialChars = "+-*/".ToCharArray();
        int indexOf = textBox1.Text.IndexOfAny(SpecialChars);
        if (indexOf == -1)
         {
          textBox1.Text = string.Empty;
          MessageBox.Show("Enter Valid Character")
         }
       }
     }