C#中textbox只能输入数字

时间:2022-06-26 12:41:47

textbox只能输入数字

 

方法一:

private void textBox7_KeyPress(object sender, KeyPressEventArgs e)//只能输入数字和.

{

    byte[] array = System.Text.Encoding.Default.GetBytes(e.KeyChar.ToString());

    if (!char.IsDigit(e.KeyChar) || array.LongLength == 2) e.Handled = true;

    if (e.KeyChar == '/b' || e.KeyChar == '.') e.Handled = false;

}

 

方法二:

private void textBox7_KeyPress(object sender, KeyPressEventArgs e)//只能输入数字和.  但不能输入小数

{

    if (!(e.KeyChar >= '0' && e.KeyChar <= '9')) e.Handled = true;

    if (e.KeyChar == '/b' || e.KeyChar == '.') e.Handled = false;

}

 

方法三:

private void textBox7_KeyPress(object sender, KeyPressEventArgs e)//需求数量栏位,只能输入数字,并且可以输入小数

{

    if (e.KeyChar != 13 && e.KeyChar != 8 && !char.IsDigit(e.KeyChar) && e.KeyChar != 46)   e.Handled = true;

    int a = textBox7.Text.IndexOf('.');

    if (e.KeyChar == 46 && a > 0)  e.Handled = true;

}