keypress event for number in WinForm TextBox in C#

▼魔方 西西 提交于 2021-01-27 21:50:21

问题


I want to limit user to type just numbers in TextBox. I add this code In keypress Event:

private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (((e.KeyChar >= '0') && (e.KeyChar <= '9')) == false)
        {
            e.Handled = true;
        }
    }

but after that BackSpace key don't work for this TextBox. How can I change this?


回答1:


You can check for backspace using this,

if(e.KeyChar == '\b') 

And better way to check only for numbers is

private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);
    }



回答2:


private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
 if (!(Char.IsDigit(e.KeyChar) && (e.KeyChar == (char)Keys.Back)))

  e.Handled = true;

}



回答3:


I think you should handle both back key and delete key.

if (!(Char.IsDigit(e.KeyChar) && (e.KeyChar == (char)Keys.Back)&& (e.KeyChar == (char)Keys.Delete)))
e.Handled = true;



回答4:


You can use it

private void txtColumn_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (((e.KeyChar >= '0') && (e.KeyChar <= '9') || (e.KeyChar == (char)Keys.Back)) == false)
        {
            e.Handled = true;
        }
    }


来源:https://stackoverflow.com/questions/29092456/keypress-event-for-number-in-winform-textbox-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!