C#--关于事件的定义及注册,如何实现在一个文本框中只输入数字或者只能输入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)
        {
            
        }

        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;
            }

         
       
       
          
        }
     
        
    }
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值