//绑定事件
txtBox.KeyPress += new KeyPressEventHandler(KeyNum);
/**/
/// <summary>
/// 只允许输入数字的方法
/// <param name="sender">事件枸柄</param>
/// <param name="e">触发事件</param>
/// </summary>
public void KeyNum(object sender, KeyPressEventArgs e)
{
if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.Handled = true;
} else if (Char.IsPunctuation(e.KeyChar))
{
String text = ((TextBox)sender).Text;
if (e.KeyChar == '.')
{
if (text.LastIndexOf(e.KeyChar) != -1)
{
e.Handled = true;
}
}
else if (e.KeyChar == '-')
{
if (text.Length != 0)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}
}