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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
this.label1.Text = this.textBox1.Text;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
this.label1.Text = this.textBox2.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
}
}
}
}
感言:在实现的过程中,要用到KeyPress事件,但是在实现这个事件时,你要将这个事件在Form1_Load里面对这个事件进行注册,也就是上文的 this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);这步是关键。
下面是一个只能输入0至9十种数字、a至z或A至Z五十二种字符。
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
this.label1.Text = this.textBox1.Text;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
this.label1.Text = this.textBox2.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//4.参照教材P162页,设计一个窗体。窗体上有一个文本框,该文本框中只能输入0至9十种数字、a至z或A至Z五十二种字符。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ( e.KeyChar<'0'|| e.KeyChar>'Z')
{ e.Handled = false;
}
}
}
}