C# textbox實時輸入值檢測方式
更新時間:2023年07月12日 15:48:30 作者:書香玫瑰
這篇文章主要介紹了C# textbox實時輸入值檢測方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
C# textbox實時輸入值檢測
檢查textbox實時輸入值是否為英文狀態(tài)下的,分割符與數值(數值可正可負)
private void textBoxMarker_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '-' || e.KeyChar == ',') { e.Handled = false;//允許輸入 } else { e.Handled = true;//不允許輸入 MessageBox.Show("請輸入整型字符(如“-5”“-10”“2”“3”)!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
C#限制TextBox控件內輸入值的范圍
舉個例子:
比如要限制TextBox1控件內只能輸入1~100的數字(先將TextBox1的MaxLength屬性設置成3):
1.首先要限制輸入的只能是數值
不能是字母或其他符號;選擇添加textBox1的KeyPress事件,代碼如下:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) ? ? ? ? { ? ? ? ? ? ? if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8) ? ? ? ? ? ? ? ? e.Handled = true; ? ? ? ? }
2.再限制輸入數值的范圍1~100
選擇添加textBox1的TextChanged事件,代碼如下:
private void textBox1_TextChanged(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? if (textBox1.Text == "")? ? ? ? ? ? ? ?? ?textBox1.Text = 0.ToString();? ? ? ? ? ? ? int number = int.Parse(textBox1.Text); ? ? ? ? ? ? textBox1.Text = number.ToString(); ? ? ? ? ? ? if (number <= 100) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? return; ? ? ? ? ? ? } ? ? ? ? ? ? textBox1.Text = textBox1.Text.Remove(2); ? ? ? ? ? ? textBox1.SelectionStart = textBox1.Text.Length; ? ? ? ? }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。