一、 textBox控件實現只允許為數字和小數點
如下圖所示,在textBox
控件框內輸入只能是
要在textBox
控件屬性設置按鍵按下的事件觸發,如下圖所示:
二、源代碼
textBox控件只允許為數字和小數點:
private void textBoxVolMax_KeyPress(object sender, KeyPressEventArgs e) { //判斷按鍵是不是要輸入的類型 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 (textBoxVolMax.Text.Length <= 0) e.Handled = true; //小數點不能在第一位 else { float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(textBoxVolMax.Text, out oldf); b2 = float.TryParse(textBoxVolMax.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } } }
把數字提取出來:
if (textBoxVolMax.Text == "") //textBoxVolMax輸入框為空不去處理 { } else { Double MaxValue = Convert.ToDouble(textBoxVolMax.Text);//將字符串轉換為數字 textBoxVolMin.Text = MaxValue.ToString(); }
轉載:cnblogs.com/yangxuli/p/8692926.html