日期:2014-05-19  浏览次数:20943 次

textBox和keypress
我想问的是在textBox框中输入非0-9数字时,textBox自动忽略掉,
例如说我在输入123后再按个K进去,但不充许K显示,怎么搞?

------解决方案--------------------
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0 ' || e.KeyChar > '9 ')
{
e.Handled = true;
}
}
------解决方案--------------------
给您一个“限制文本框的输入”的例子:
1、在 Microsoft Visual Studio .NET 的“文件”菜单上,单击“新建”,然后单击“项目”。
2、在“新建项目”对话框中,选择“Visual C#项目”,再选择“Windows 应用程序”模板。
3、键入 TextApp 作为该程序的名称,然后单击确定。
4、在Form1.cs的视图设计器中,添加如下控件:
控件类型 控件名称  控件属性 属性值
Label label1 Text 输入十进制数
Label label2 Text 输入大写字母
TextBox textBox1
TextBox textBox2
5、在Form1.cs的视图设计器中,选中textBox1,在属性框中选中事件,双击KeyPress,在Form1.cs的代码设计器中,添加修改如下代码
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsNumber(e.KeyChar) || (Keys)e.KeyChar == Keys.Back || e.KeyChar.ToString() == ". ")
e.Handled = false;//允许输入
else
e.Handled = true;//取消输入
}
6、在Form1.cs的视图设计器中,选中textBox2,在属性框中选中事件,双击KeyPress,在Form1.cs的代码设计器中,添加修改如下代码
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsUpper(e.KeyChar) || (Keys)e.KeyChar == Keys.Back)
e.Handled = false;//允许输入
else
e.Handled = true;//取消输入
}
7、编译


要想轻松开发软件,详见http://www.psec.net.cn