C# textbox實時輸入值檢測方式
更新時間:2023年07月12日 15:48:30 作者:書香玫瑰
這篇文章主要介紹了C# textbox實時輸入值檢測方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
C# textbox實時輸入值檢測
檢查textbox實時輸入值是否為英文狀態(tài)下的,分割符與數(shù)值(數(shù)值可正可負)
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控件內(nèi)輸入值的范圍
舉個例子:
比如要限制TextBox1控件內(nèi)只能輸入1~100的數(shù)字(先將TextBox1的MaxLength屬性設置成3):
1.首先要限制輸入的只能是數(shù)值
不能是字母或其他符號;選擇添加textBox1的KeyPress事件,代碼如下:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
? ? ? ? {
? ? ? ? ? ? if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
? ? ? ? ? ? ? ? e.Handled = true;
? ? ? ? }2.再限制輸入數(shù)值的范圍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;
? ? ? ? }總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

