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
}
}
注意:次の文字 (表示されていません)は、バックスペースを表します。
注意: を使用して、特定の文字を常に許可または禁止することができますe.Handled
。
注意-
: 、
、(
またはを 1 回だけ使用する場合は、条件ステートメントを作成できます)
。これらの文字を特定の位置に入力できるようにする場合は、正規表現を使用することをお勧めします。
例
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;
}
}
ありがとう、
これがお役に立てば幸いです:)