轉載:https://blog.csdn.net/qq_48705696/article/details/108929310
1.為文本框添加KeyPress事件:
2.輸入限制的原理:將輸入值轉化為ACSII的值進行限制,附上ACSII表
(我猜你看不清這圖片,在圖片上右擊——>新標簽頁中打開圖片)
3.原理大致明了了,接下來編程
/// <summary> /// KeyPress事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { limit_txtinput(sender, e); } private void limit_txtinput(object sender, KeyPressEventArgs e) { //ACSII中48-57表示數字:0-9 //ACSII中8表示退格鍵(刪除鍵) //ACSII中46表示小數點 if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46) e.Handled = true; //小數點的處理。 if ((int)e.KeyChar == 46) //小數點 { if (this.Text.Length <= 0) e.Handled = true; //小數點不能在第一位 else { float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(this.Text, out oldf); b2 = float.TryParse(this.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } } }
4.原作者的可輸入負號版本(只轉載,未經驗證)
private void t_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = limit_txtinput(sender, e); } //限制txtBox的輸入內容僅可為數字和小數點(小數點不能是首位) private bool limit_txtinput(object sender, KeyPressEventArgs e) { //允許輸入數字、小數點、刪除鍵和負號 if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-')) return true; if (e.KeyChar == (char)('-')) { if ((sender as TextBox).Text != "") return true; } //小數點只能輸入一次 if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1) return true; //第一位不能為小數點 if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "") return true; //第一位是0,第二位必須為小數點 if (e.KeyChar != (char)('.') && e.KeyChar != 8 && ((TextBox)sender).Text == "0") return true; //第一位是負號,第二位不能為小數點 if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.')) return true;
return false; }