首先設置只可以輸入數字:
首先設置TextBox控件的KeyPress事件:當用戶按下的鍵盤的鍵不在數字位的話,就禁止輸入
1 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 2 { 3 if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))//如果不是輸入數字就不讓輸入 4 { 5 e.Handled = true; 6 } 7 }
設置上限:
設置TextBox的TextChanged事件如下
1 private void textBox1_TextChanged(object sender, EventArgs e) 2 { 3 int iMax = 100;//首先設置上限值 4 if (textBox1.Text != null && textBox1.Text != "")//判斷TextBox的內容不為空,如果不判斷會導致后面的非數字對比異常 5 { 6 if (int.Parse(textBox1.Text) > iMax)//num就是傳進來的值,如果大於上限(輸入的值),那就強制為上限-1,或者就是上限值? 7 { 8 textBox1.Text = (iMax - 1).ToString(); 9 } 10 } 11 }