由於項目需要,需要寫一個TextBox文本框,此文本框需要滿足:只能輸入正數,負數和小數。比如:3,0.3,-4,-0.4等等。
在網上找了許多正則表達式都不好用,由於本人又對正則表達式一竅不通,就換了一種方式。使用了TextBox的KeyPress事件,完成了上述需求。這點代碼寫了一下午有木有,下面分享給大家。
代碼如下:
C#代碼
/*
*設置textBox只能輸入數字(正數,負數,小數)
*/
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//允許輸入數字、小數點、刪除鍵和負號
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
{
MessageBox.Show("請輸入正確的數字");
this.textBox1.Text = "";
e.Handled = true;
}
if (e.KeyChar == (char)('-'))
{
if (textBox1.Text != "")
{
MessageBox.Show("請輸入正確的數字");
this.textBox1.Text = "";
e.Handled = true;
}
}
//小數點只能輸入一次
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
{
MessageBox.Show("請輸入正確的數字");
this.textBox1.Text = "";
e.Handled = true;
}
//第一位不能為小數點
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
{
MessageBox.Show("請輸入正確的數字");
this.textBox1.Text = "";
e.Handled = true;
}
//第一位是0,第二位必須為小數點
if (e.KeyChar != (char)('.') && ((TextBox)sender).Text == "0")
{
MessageBox.Show("請輸入正確的數字");
this.textBox1.Text = "";
e.Handled = true;
}
//第一位是負號,第二位不能為小數點
if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
{
MessageBox.Show("請輸入正確的數字");
this.textBox1.Text = "";
e.Handled = true;
}
控制只能輸入整數或小數(供TextBox注冊KeyPress事件)#region 控制只能輸入整數或小數(供TextBox注冊KeyPress事件)
/**//// <summary>
/// 控制只能輸入整數或小數
/// (小數位最多位4位,小數位可以自己修改)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Txb_Decimal_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
{
if(e.KeyChar == '.')
{
if ( ((TextBox)sender).Text.Trim().IndexOf('.') > -1)
e.Handled = true;
}
else
e.Handled = true;
}
else
{
if( e.KeyChar <= 31 )
{
e.Handled = false ;
}
else if( ((TextBox)sender).Text.Trim().IndexOf('.') > -1 )
{
if( ((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1 ).Length >= 4)
e.Handled = true ;
}
}
}
#endregion