如何使用C#验证文本框值是否唯一 [英] How Do I Validate Textboxes Values To Be Unique using C#
问题描述
我有12个文本框,我正在尝试找到一种策略,允许用户在运行时不允许TextBox中的重复条目。
这里是我想要实现的目标:
1.在任何文本框中输入值时,不允许复制已在任何其他TextBox中输入的值。
2.允许复制感叹号(!)。
例如:如果第一个文本框仅包含1个感叹号(!)然后所有其他文本框都可以接受感叹号的副本。
列表< string> lstTextBoxes = new List< string>();
private void HCFA_21_Diag1_Leave( object sender,EventArgs e)
{
lstTextBoxes.Add(HCFA_21_Diag1.Text);
}
public bool lstCheck(List< string> lstTextBoxes, string input)
{
if (lstTextBoxes.Contains(input))
{
return 真跨度>;
}
其他
{
返回 假跨度>;
}
}
private void HCFA_21_Diag2_Leave( object sender,EventArgs e)
{
lstTextBoxes.Add(HCFA_21_Diag2.Text);
if (lstCheck(lstTextBoxes,HCFA_21_Diag2.Text))
{
MessageBox.Show( test);
}
}
}
你走在正确的轨道上 - 在某种程度上。
但是......我每次进行验证时都会构建列表(否则,如果用户返回并更改它们,则可以在当前测试中包含旧字符串。 )
多个文本框只包含!允许 - 所以当你将它们添加到你的列表时检查:
List< string> boxes = new List< string>();
foreach (控制c 在控件中)
{
Textbox tb = c as TextBox;
if (tb!= null )
{
if (tb.Text!= ! )boxes.Add(tb.Text);
}
}然后,对列表进行排序:
boxes.Sort();现在,如果有任何重复,它们在列表中是并排的,所以通过检查前一个列表条目的简单循环将告诉您是否有任何重复:
< pre lang =c#> string last = ! 跨度>; // 我们知道框中不包含这些
foreach (字符串 s 在框中)
{
if (s == last)
{
MessageBox.Show( < span class =code-string>复制: + s);
break ;
}
last = s;
}
让我向您展示解决方案结构的一些想法,我想知道您可以在多大程度上编写解决方案必需代码:我假设你在名为'TBPanel的面板中有12个TextBox,名为TextBox1~TextBox12。
这使用字典< TextBox,string> ;存储每个TextBox的当前.Text属性。private const < span class =code-keyword> string Exclam = !;
private TextBox leftTextBox;
private bool tbOneHasExclam = 假跨度>;
private string leftTextBoxOldContent;
private string leftTextBoxNewContent;
私人字典< TextBox,字符串> dctTBToStr = new 字典< TextBox,string>();
private void YourMainForm_Load(对象发件人,EventArgs e)
{
foreach (TextBox tb in TBPanel.Controls.OfType< textbox>())
{
// connect a '离开EventHandler
tb.Leave + = TextBoxes_Leave;
// 添加到词典
dctTBToStr.Add(tb , String .Empty);
}
}
私有 void TextBoxes_Leave( object sender,EventArgs e)
{
leftTextBox = sender as TextBox;
leftTextBoxOldContent = dctTBToStr [leftTextBox];
leftTextBoxNewContent = leftTextBox.Text;
// 如果内容未更改,请继续
if (leftTextBoxOldContent == leftTextBoxNewContent) return ;
// 如果新内容为则更新并继续
if (leftTextBoxNewContent == String .Empty)
{
dctTBToStr [leftTextBox] = String .Empty;
return ;
}
// 现在好玩的开始了!
CheckForDuplicateEntry();
}
private void CheckForDuplicateEntry()
{
switch (leftTextBox.Name)
{
// TextBox1已更改
case TextBox1:
// update
dctTBToStr [TextBox1] = leftTextBoxNewContent;
// 测试!
tbOneHasExclam = leftTextBoxNewContent == Exclam;
// 如果TextBoxOne是或!
// 我们可以继续
if (tbOneHasExclam || leftTextBoxNewContent == String .Empty) break ;
// 这里需要做什么?
// 我们知道TextBox1不是!
// 我们需要找到
// <的任何其他TextBox span class =code-comment>!的文本和一个可能的TextBox
// 其中text == TextBox1.Text
// 构建要清除的TextBoxes集合
// 以避免收到修改错误:
// 我们无法修改'for或'foreach循环中的Dictionary值
List< ;文本框> duplicates = null ;
foreach (TextBox tb in dctTBToStr.Keys)
{
// 忽略可以跳过的内容
if (tb.Text == String .Empty || tb == TextBox1)继续跨度>;
if (tb.Text == leftTextBoxNewContent || tb.Text == Exclam)
{
重复。添加(TB);
}
}
如果(重复!= null )
{
for ( int i = 0 ; i < duplicates.Count; i ++)
{
TextBox duplicate = duplicates [i] ;
duplicate.Clear();
dctTBToStr [duplicate] = String .Empty;
}
}
break ;
// 所有其他TextBox中的流程更改
默认:
// 现在......你写代码
break ;
}
}
我自己已经解决了这个问题。
//使用控制类。
//此代码适用于3个文本框。
公共部分类Form2:表格
{
int totalCtrl = 3;
public Form2()
{
InitializeComponent();
}
private void HCFA_21_Diag1_Leave(object sender,EventArgs e)
{
if(IsDuplicate(1))
MessageBox.Show(重复值!);
}
private bool IsDuplicate(string keyedID)
{
bool isDuplicate = false;
string fieldName =HCFA_21_Diag;
控制ctrl = this.Controls [fieldName + keyedID];
if(ctrl.Text!=!&& ctrl.Text!= string.Empty)
{
for(int i = 1; i< = totalCtrl; i ++)
{
Control allCtrl = this.Controls [fieldName + i.ToString()];
if(ctrl.Text == allCtrl.Text&& ctrl.Name!= allCtrl.Name)
{
isDuplicate = true;
休息;
}
}
}
return isDuplicate;
}
private void HCFA_21_Diag2_Leave(object sender,EventArgs e)
{
if(IsDuplicate(2))
MessageBox.Show(重复值!);
}
private void HCFA_21_Diag3_Leave(object sender,EventArgs e)
{
if(IsDuplicate(3))
MessageBox.Show(重复值!);
}
}
}
I have 12 text boxes, and I am trying to find a strategy to not permit duplicate entries in the TextBoxes by the user at run-time.
Here's what I'm trying to achieve:
1. While entering values in any Textbox, duplication of a value already entered in any other TextBox is not allowed.
2. Duplication of exclamation mark (!) is allowed.
For Ex : If first textbox contains only 1 exclamation mark(!) then all other textbox can accept duplicate of exclamation mark.
List<string> lstTextBoxes = new List<string>();
private void HCFA_21_Diag1_Leave(object sender, EventArgs e)
{
lstTextBoxes.Add(HCFA_21_Diag1.Text);
}
public bool lstCheck(List<string> lstTextBoxes,string input)
{
if(lstTextBoxes.Contains(input))
{
return true;
}
else
{
return false;
}
}
private void HCFA_21_Diag2_Leave(object sender, EventArgs e)
{
lstTextBoxes.Add(HCFA_21_Diag2.Text);
if (lstCheck(lstTextBoxes, HCFA_21_Diag2.Text))
{
MessageBox.Show("test");
}
}
}
You are on the right track - to an extent.
But...I'd build the list when I did the validation each time (otherwise you could include "old" strings in current tests if the user goes back and changes them.)
Multiple textboxes containing just "!" is allowed - so check that when you add them to your list:
List<string> boxes = new List<string>(); foreach (Control c in Controls) { Textbox tb = c as TextBox; if (tb != null) { if (tb.Text != "!") boxes.Add(tb.Text); } }Then, sort the list:
boxes.Sort();Now, if there are any duplicates, they are side-by-side in the list, so a simple loop through checking against the previous list entry will tell you if there are any duplicates:
string last = "!"; // We know that boxes contains none of these foreach (string s in boxes) { if (s == last) { MessageBox.Show("Duplicate: " + s); break; } last = s; }
Let me show you some ideas for the structure of a solution, and I'd like to see how far you can get writing the required code: I'm going to assume you have 12 TextBoxes, named TextBox1~TextBox12, in a Panel named 'TBPanel.
This uses a Dictionary<TextBox, string> to store the current .Text property of each TextBox.private const string Exclam = "!"; private TextBox leftTextBox; private bool tbOneHasExclam = false; private string leftTextBoxOldContent; private string leftTextBoxNewContent; private Dictionary<TextBox, string> dctTBToStr = new Dictionary<TextBox, string>(); private void YourMainForm_Load(object sender, EventArgs e) { foreach (TextBox tb in TBPanel.Controls.OfType<textbox>()) { // connect a 'Leave EventHandler tb.Leave += TextBoxes_Leave; // add to Dictionary dctTBToStr.Add(tb, String.Empty); } } private void TextBoxes_Leave(object sender, EventArgs e) { leftTextBox = sender as TextBox; leftTextBoxOldContent = dctTBToStr[leftTextBox]; leftTextBoxNewContent = leftTextBox.Text; // if the content hasn't changed, keep going if (leftTextBoxOldContent == leftTextBoxNewContent) return; // if the new content is "" then update and keep going if(leftTextBoxNewContent == String.Empty) { dctTBToStr[leftTextBox] = String.Empty; return; } // now the fun begins ! CheckForDuplicateEntry(); } private void CheckForDuplicateEntry() { switch (leftTextBox.Name) { // TextBox1 has changed case "TextBox1": // update dctTBToStr[TextBox1] = leftTextBoxNewContent; // test for "!" tbOneHasExclam = leftTextBoxNewContent == Exclam; // if TextBoxOne is "" or "!" // we can keep going if (tbOneHasExclam || leftTextBoxNewContent == String.Empty) break; // what needs to happen here ? // we know that TextBox1 is not "!" // we need to find any other TextBoxes with // text of "!" and the one possible TextBox // where its text == TextBox1.Text // build a collection of TextBoxes to be cleared // in order to avoid getting a modify collection error: // we can't modify a Dictionary value in a 'for or 'foreach loop List<textbox> duplicates = null; foreach (TextBox tb in dctTBToStr.Keys) { // ignore what can be skipped over if (tb.Text == String.Empty || tb == TextBox1) continue; if (tb.Text == leftTextBoxNewContent || tb.Text == Exclam) { duplicates.Add(tb); } } if (duplicates != null) { for (int i = 0; i < duplicates.Count; i++) { TextBox duplicate = duplicates[i]; duplicate.Clear(); dctTBToStr[duplicate] = String.Empty; } } break; // process change in all other TextBoxes default: // and now ... you write the code break; } }
I have solved this question myself.
// Using control class.
// this code is for 3 textboxes.
public partial class Form2 : Form { int totalCtrl = 3; public Form2() { InitializeComponent(); } private void HCFA_21_Diag1_Leave(object sender, EventArgs e) { if (IsDuplicate("1")) MessageBox.Show("Is duplicate value!"); } private bool IsDuplicate(string keyedID) { bool isDuplicate = false; string fieldName = "HCFA_21_Diag"; Control ctrl = this.Controls[fieldName + keyedID]; if (ctrl.Text != "!" && ctrl.Text != string.Empty) { for (int i = 1; i <= totalCtrl; i++) { Control allCtrl = this.Controls[fieldName + i.ToString()]; if (ctrl.Text == allCtrl.Text && ctrl.Name != allCtrl.Name) { isDuplicate = true; break; } } } return isDuplicate; } private void HCFA_21_Diag2_Leave(object sender, EventArgs e) { if (IsDuplicate("2")) MessageBox.Show("Is duplicate value!"); } private void HCFA_21_Diag3_Leave(object sender, EventArgs e) { if (IsDuplicate("3")) MessageBox.Show("Is duplicate value!"); } } }
这篇关于如何使用C#验证文本框值是否唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!