开发者

how to make textbox who only allow integer value?

i want to make a textbox in my wpf application开发者_StackOverflow中文版 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


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;
    }
}


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

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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜