Domanda

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.

È stato utile?

Soluzione

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")
     }
   }
 }

Altri suggerimenti

Use a regular TextBox. MaskedTextBox won't meet your needs. In a very simple form example, use an event handler like this for KeyPress on the TextBox:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
  var accepted = new[] {'+', '-', '*', '/', (char)Keys.Back};
  if (!accepted.Intersect(new[] {e.KeyChar}).Any()) {
    e.Handled = true;
  }
}

and set the TextBox.MaxLength property to 1.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top