日期:2014-05-18  浏览次数:21031 次

如何限置“textbox”控件只能输入特定的数字与字符?
求教:现在限定了textbox控件只能输入0-9数字,如何增加还能输入一个字符“.”?

比如能输入“9.5”、“10.22”

代码如下:
C# code

private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
            nonNumberEntered = false;
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9 )
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 )
                {
                    if (e.KeyCode != Keys.Back)
                    {
                        nonNumberEntered = true;
                    }
                }
            }
        }
        private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (nonNumberEntered == true)
            {
                e.Handled = true;
            }
        }



------解决方案--------------------
try
{
double x = Convert.ToDouble(TextBox1.Text);
}
catch
{
MessageBox.Show("非法的数字!");
}
------解决方案--------------------
增加等于 '.'的判断,或者用正则
C# code

private void textBox1_Validating(object sender, CancelEventArgs e) 
{ 
const string pattern = @"^\d+\.?\d+$"; 
string content = ((TextBox)sender).Text; 

if (!(Regex.IsMatch(content, pattern))) 
{ 
MessageBox.Show( "只能输入数字!"); 
e.Cancel = true; 
} 
else 
xxxxxxx
}