How do I make a textbox that only accepts numbers?

后端 未结 30 2130
梦如初夏
梦如初夏 2020-11-21 06:05

I have a windows forms app with a textbox control that I want to only accept integer values. In the past I\'ve done this kind of validation by overloading the KeyPress event

30条回答
  •  春和景丽
    2020-11-21 06:40

    This is my aproach:

    1. using linq (easy to modify filter)
    2. copy/paste proof code
    3. keeps caret position when you press a forbidden character
    4. accepts left zeroes
    5. and any size numbers

      private void numeroCuenta_TextChanged(object sender, EventArgs e)
      {
          string org = numeroCuenta.Text;
          string formated = string.Concat(org.Where(c => (c >= '0' && c <= '9')));
          if (formated != org)
          {
              int s = numeroCuenta.SelectionStart;
              if (s > 0 && formated.Length > s && org[s - 1] != formated[s - 1]) s--;
              numeroCuenta.Text = formated;
              numeroCuenta.SelectionStart = s;
          }
      }
      

提交回复
热议问题