0

電話番号を挿入するためのテキストボックスを作成しました。数字、削除ボタン、ハイフンキーだけを押してほしい。私は次のコードを使用しました:それは削除ボタンと数字のために働きます、私はハイフンのために何をすべきですか?

private void ContactNumTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    const char Hyphen = (char)2d;
    const char Delete = (char)8;
    if (char.IsNumber(e.KeyChar) && e.KeyChar != Hyphen && e.KeyChar!= Delete)
        e.Handled = true; 
}
4

2 に答える 2

3

16進数を使用する場合は、番号の前に。を付ける必要があります0xd数値がdoubleであることを指定する偶然の一致により、現在、コードはコンパイルされています。次のコードは、ハイフンを正しく検出します。

private void ContactNumTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    const char hyphen = (char)0x2D;
    const char delete = (char)0x08;
    if (!char.IsNumber(e.KeyChar) && e.KeyChar != hyphen && e.KeyChar!= delete)
        e.Handled = true; 
}
于 2013-03-25T05:34:41.350 に答える
0

これも試すことができます

if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '-'))
{
     e.Handled = true;

}
于 2018-07-10T05:54:06.977 に答える