delete my account
delete my account

Reputation:

how to make textbox who only allow integer value?

i want to make a textbox in my wpf application which will accept only integer values. if someone types characters between [a-z], the textbox will reject it. Thus it will not be displayed in the textbox

Upvotes: 3

Views: 8875

Answers (5)

Matěj Zábský
Matěj Zábský

Reputation: 17272

Bind it to Integer property. WPF will do the validation itself without any extra hassle.

Upvotes: 1

Jogy
Jogy

Reputation: 2475

You can handle the PreviewTextInput event:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // Filter out non-digit text input
  foreach (char c in e.Text) 
    if (!Char.IsDigit(c)) 
    {
      e.Handled = true;
      break;
    }
}

Upvotes: 7

Can Gencer
Can Gencer

Reputation: 8885

this simple code snippet should do the trick.. You might also want to check for overflows (too large numbers)

private void IntegerTextBox_TextChanged(object sender, EventArgs e)
{
    for (int i = 0; i < Text.Length; i++)
    {
        int c = Text[i];
        if (c < '0' || c > '9')
        {
           Text = Text.Remove(i, 1);
         }
    }
}

Upvotes: 1

kyrylomyr
kyrylomyr

Reputation: 12642

You can add handle of the TextChanged event and look what was entered (need to check all text every time for preventing pasting letters from clipboard).

Also look a very good example of creating maskable editbox on CodeProject.

Upvotes: 1

John Gietzen
John Gietzen

Reputation: 49564

In WPF, you can handle the KeyDown event like this:

private void MyTextBox_KeyDown(object sender, KeyDownEventArgs e)
{
    e.Handled = true;
}

Upvotes: 1

Related Questions