C#中只接受数字输入的控件
2009-06-04 08:30:14 来源:WEB开发网核心提示: 运行程序,在输入任意非0-9的字符时的样子: (截图反映的是在我的简体中文Windows XP上的运行效果;若系统语言不是简体中文的话会根据系统语言而不同) 如果这个文本框已经能满足需求,C#中只接受数字输入的控件(3),就没必要自己监听KeyDown事件那么麻烦了, 二、自行监听KeyD
运行程序,在输入任意非0-9的字符时的样子:
(截图反映的是在我的简体中文Windows XP上的运行效果;若系统语言不是简体中文的话会根据系统语言而不同)
如果这个文本框已经能满足需求,就没必要自己监听KeyDown事件那么麻烦了。
二、自行监听KeyDown事件
可以参考CodeProject上Numeric TextBox : Allow your users to enter numeric data the easy way的实现方式。基本原理就是在KeyDown的响应方法中对e.KeyCode进行判断,如果输入不满足条件则设置某个标识,然后再KeyPress的响应方法里设置e.Handled = true;来取消该次事件。
最简单来说类似这样:
C#代码
using System;
using System.Drawing;
using System.Windows.Forms;
sealed class TestForm : Form
{
private TextBox m_textBox;
private bool m_nonNumberEntered = false;
public TestForm() {
InitializeComponent();
}
private void InitializeComponent() {
this.m_textBox = new TextBox();
this.m_textBox.Dock = DockStyle.Fill;
this.m_textBox.KeyDown += m_textBox_KeyDown;
this.m_textBox.KeyPress += m_textBox_KeyPress;
this.ClientSize = new Size(100, 60);
this.Controls.Add(this.m_textBox);
this.PerformLayout();
}
private void m_textBox_KeyDown(object sender, KeyEventArgs e) {
// Initialize the flag to false.
m_nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9) {
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9) {
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back) {
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
m_nonNumberEntered = true;
}
}
}
}
private void m_textBox_KeyPress(object sender, KeyPressEventArgs e) {
// Check for the flag being set in the KeyDown event.
if (m_nonNumberEntered) {
// Stop the character from being entered into the control
// since it is non-numerical.
e.Handled = true;
}
}
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm());
}
}
更多精彩
赞助商链接