テキストボックスで文字の入力を制限する - テキストボックスで数値のみ入力を受け付ける - C#
テキストボックスで文字の入力を制限するコードを紹介します。
UI
以下のUIを作成します。
KeyPressイベントを利用
KeyPressイベントを用いてテキストボックスへの文字の入力を制限する方法です。
コード
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NumericTextBox
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ('0' <= e.KeyChar && e.KeyChar <= '9') {
}
else if(e.KeyChar == '\b'){
}
else {
e.Handled = true;
}
}
}
}
KeyPressイベントを利用
KeyDownイベントを利用する場合のコードです。
コード
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NumericTextBox
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (Keys.D0 <= e.KeyCode && e.KeyCode <= Keys.D9) {
e.Handled = false;
}
else if (Keys.NumPad0 <= e.KeyCode && e.KeyCode <= Keys.NumPad9) {
e.Handled = false;
}
else if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back) {
e.Handled = false;
}
else if (e.KeyCode == Keys.Tab) {
e.Handled = false;
}
else if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right
|| e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) {
e.Handled = false;
}
else {
e.Handled = true;
e.SuppressKeyPress = true;
}
}
}
}
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
数字以外のキーを押してもテキストボックスには入力されません。
注意
クリップボードからの貼り付けでは文字が入力できてしまいます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用