由於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;
}
}
謝謝,
我希望對您有所幫助:)
'txtHomePhone'代表一個'TextBox'嗎?如果是這樣,你可以使用'KeyPress'事件來接受你想要允許的字符,並拒絕你不想在'TextBox'中輸入的內容。有一個美好的一天:) –
它確實代表一個文本框,我如何找出哪個按鍵是哪個? – Wizard
這是一個網絡或客戶端應用程序? –