Possible Duplicate:
How do I make a textbox that only accepts numbers?
我有一个电话号码,我希望将其存储为一个字符串。
我在使用中阅读了这个
txtHomePhone.Text
我想我需要的是某种数字但无法让它工作
if (txtHomePhone.Text == //something.IsNumeric)
{
//Display error
}
else
{
//Carry on with the rest of program ie. Add Phone number to program.
}
只允许输入数值的最佳方法是什么?
由于 txtHomePhone
代表一个 TextBox
,您可以使用 KeyPress
事件来接受您想要允许的字符并拒绝您想要的字符不喜欢在 txtHomePhone
中允许
示例
public Form1()
{
InitializeComponent();
txtHomePhone.KeyPress += new KeyPressEventHandler(txtHomePhone_KeyPress);
}
private void txtHomePhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The character represents a backspace
{
e.Handled = false; //Do not reject the input
}
else
{
e.Handled = true; //Reject the input
}
}
通知:The following character (which is not visible) represents a backspace.
注意:您始终可以使用e.Handled
允许或禁止特定字符。
注意:如果您想使用-
、
,您可以创建一个条件语句>、(
或 )
仅一次。如果您希望允许在特定位置输入这些字符,我建议您使用正则表达式。
示例
if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The character represents a backspace
{
e.Handled = false; //Do not reject the input
}
else
{
if (e.KeyChar == ')' && !txtHomePhone.Text.Contains(")"))
{
e.Handled = false; //Do not reject the input
}
else if (e.KeyChar == '(' && !txtHomePhone.Text.Contains("("))
{
e.Handled = false; //Do not reject the input
}
else if (e.KeyChar == '-' && !textBox1.Text.Contains("-"))
{
e.Handled = false; //Do not reject the input
}
else if (e.KeyChar == ' ' && !txtHomePhone.Text.Contains(" "))
{
e.Handled = false; //Do not reject the input
}
else
{
e.Handled = true;
}
}
谢谢,
希望这对您有所帮助:)