C#实现输入内容长度检查

 时间:2024-10-14 04:27:04

1、在建一个winfrom项目,在上面添加两个label控件和两个textbox控件,一个用于填写要管控的长度设置,一个用来接收录入的数据。

C#实现输入内容长度检查

2、编写检查函数checklength().先把两个textbox框中的长度确定出来。 private void checklength() { int m = int.Parse(textBox1.Text); int n = textBox2.Text.Length; }

C#实现输入内容长度检查

3、判断语句编写。private void checklength() { int m = int.Parse(textBox1.Text);//定义长度 int n = textBox2.Text.Length;//录入内容长度 if (m != n) { MessageBox.Show("输入长度错误!"); } else { MessageBox.Show("OK!"); }

C#实现输入内容长度检查

4、完善下代码,条码长度错误以后让输入框变为红色,并把输入内容全部选中。 private void checklength() { int m = int.Parse(textBox1.Text);//定义长度 int n = textBox2.Text.Length;//录入内容长度 if (m != n) { MessageBox.Show("输入长度错误!"); textBox2.BackColor = Color.Red; textBox2.SelectAll(); } else { MessageBox.Show("OK!"); textBox2.BackColor = Color.White; textBox2.SelectAll(); } }

C#实现输入内容长度检查

5、利用回车事件来验证录入的内容长度是否符合自定义长度。 private void textBox2_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { checklength(); } } }

C#实现输入内容长度检查

6、验证结果符合要求,附完整源代码: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 WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void checklength() { int m = int.Parse(textBox1.Text);//定义长度 int n = textBox2.Text.Length;//录入内容长度 if (m != n) { MessageBox.Show("输入长度错误!"); textBox2.BackColor = Color.Red; textBox2.SelectAll(); } else { MessageBox.Show("OK!"); textBox2.BackColor = Color.White; textBox2.SelectAll(); } } private void textBox2_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { checklength(); } } }}

C#实现输入内容长度检查
C#实现输入内容长度检查
C#实现输入内容长度检查
  • 粤政易怎么更换聊天背景图
  • 上海广播电台有F1直播吗
  • 如何停用爱股票pro高手观点
  • 60级德巴攻略
  • 热门搜索
    二月二龙抬头的手抄报 防震减灾手抄报花边 数学乐园手抄报内容 健康知识手抄报内容 小学四年级数学手抄报 关于科技的手抄报图片 儿童手抄报春节 一年级手抄报怎么写 初一英语手抄报图片 爱国手抄报花边