在工作中,一些工作場景下,需要對我們錄入的數據做一些簡單的準確性判定。好比錄入數據的長度則是此中一種比力直不雅的判定。下面,我們以一個C#winfrom程式編寫長度驗證的布景來看看,C#事項錄入數據長度查抄的實現。
在建一個winfrom項目,在上面添加兩個label控件和兩個textbox控件,一個用于填寫要管控的長度設置,一個用來領受錄入的數據。
編寫查抄函數checklength().先把兩個textbox框中的長度確定出來。
private void checklength()
{
int m = int.Parse(textBox1.Text);
int n = textBox2.Text.Length;
}
判定語句編寫。
private void checklength()
{
int m = int.Parse(textBox1.Text);//界說長度
int n = textBox2.Text.Length;//錄入內容長度
if (m != n)
{
MessageBox.Show("輸入長度錯誤!");
}
else
{
MessageBox.Show("OK!");
}
完美下代碼,條碼長度錯誤今后讓輸入框變為紅色,并把輸入內容全數選中。
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();
}
}
}
驗證成果合適要求,附完整源代碼:
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();
}
}
}
}
0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!