c#学习-判断是否输入数字或字母

在textbox内添加keypress事件

textbox1_keypress(object sender ,EventArgs e);

代码

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 判断是否输入数字或者字母
{
    public partial class Form1 : Form
    {
        int a, b;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "请输入一串字符";
            label2.Text = "转换后的字符";
        }
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {

            if(e.KeyChar>='1'&&e.KeyChar<='9')
            {
                a++;
                e.Handled = true;
                
            }
            else if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
            {
                b++;
                e.Handled = false;
                textBox2.Text = b.ToString();
            }
            if (e.KeyChar==(char)Keys.Back)    //keys.back表示退回键
            {
                if(b==0)
                {
                    return;
                }
                b--;
                textBox2.Text = b.ToString();
            }
        }
    }
}


结果如下

发布了24 篇原创文章 · 获赞 48 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/xiaokai1999/article/details/80401151