1、利用輸入框的keypress事件
2、加入如下代碼:
//判斷只能輸入數字和Backspace
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8)
e.Handled = true;
//判斷可輸入小數點,但小數點不能放在數字的前面,且要保證只能輸入一個小數點在正確的位置
if ((int)e.KeyChar == 46) //小數點
{
if (tB_UnitPrice.Text.Length <= 0)
e.Handled = true; //小數點不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(tB_UnitPrice.Text, out oldf);
b2 = float.TryParse(tB_UnitPrice.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
else
e.Handled = false;
}
}