数字のみ入力可能なテキストボックス [.NET Framework Windows Forms]

MSDN のWebサイトで見つけたコードの覚え書きです。TextBox を継承したクラスにて OnKeyPress をオーバーライドします。

protected override void OnKeyPress ( KeyPressEventArgs e ) {

	base.OnKeyPress ( e );

	System.Globalization.NumberFormatInfo numberFormatInfo 
		= System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
	string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
	string groupSeparator = numberFormatInfo.NumberGroupSeparator;
	string negativeSign = numberFormatInfo.NegativeSign;

	string keyInput = e.KeyChar.ToString ();	

	if ( Char.IsDigit ( e.KeyChar ) ) {
		// Digits are OK
	}
	else if ( keyInput.Equals ( decimalSeparator ) 
		|| keyInput.Equals ( groupSeparator ) 
		|| keyInput.Equals ( negativeSign ) ) {
		// Decimal separator is OK
	}
	else if ( e.KeyChar == '\b' ) {
		// Backspace key is OK 
	}
	else if ( e.KeyChar == ':' ) {
		// Colon is OK.
	}
	else {
		e.Handled = true;
	}

}

使うときは、


public class NumberTextBox : TextBox {

	protected override void OnKeyPress ( KeyPressEventArgs e ) {
	
		...
		
	}
	
}

として、TextBox の派生クラスを作り、TextBox の代わりに NumberTextBox を使う。

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Web/DB プログラミング徹底解説