如何验证文本框值是否唯一

本文关键字:是否 唯一 文本 何验证 验证 | 更新日期: 2023-09-27 18:29:23

我有12个文本框,我正在努力寻找一种策略,不允许用户在运行时在文本框中重复条目。

List<string> lstTextBoxes = new List<string>();
private void Textbox1(object sender, EventArgs e)
{
   lstTextBoxes.Add(Textbox1.Text);
}
public bool lstCheck(List<string> lstTextBoxes,string input)
{
    if(lstTextBoxes.Contains(input))
    {
        return true;
    }
    else
    {
        return false;
    }
}
private void Textbox2(object sender, EventArgs e)
{
    lstTextBoxes.Add(Textbox2.Text);
    if (lstCheck(lstTextBoxes, Textbox2.Text))
    {
        MessageBox.Show("test");
    }
}

如何验证文本框值是否唯一

public bool CheckForDuplicates()
{
    //Collect all your TextBox objects in a new list...
    List<TextBox> textBoxes = new List<TextBox>
    {
        textBox1, textBox2, textBox3
    };
    //Use LINQ to count duplicates in the list...
    int dupes = textBoxes.GroupBy(x => x.Text)
                         .Where(g => g.Count() > 1)
                         .Count();
    //true if duplicates found, otherwise false
    return dupes > 0;
}

有很多方法可以实现这一点。我选择将解决方案作为扩展方法来呈现,但只需将该方法放置在包含文本框列表的类中,或将列表作为参数传递,就可以获得相同的结果。你喜欢哪一个。

将以下内容剪切并粘贴到您的项目中。确保将它放在同一个命名空间中,否则,添加包含的命名空间作为引用。

public static class TextBoxCollectionExtensions
{
    /// <summary>
    /// Extension method that determines whether the list of textboxes contains a text value.
    /// (Optionally, you can pass in a list of textboxes or keep the method in the class that contains the local list of textboxes.
    /// There is no right or wrong way to do this. Just preference and utility.)
    /// </summary>
    /// <param name="str">String to look for within the list.</param>
    /// <returns>Returns true if found.</returns>
    public static bool IsDuplicateText(this List<TextBox> textBoxes, string str)
    {
        //Just a note, the query has been spread out for readability and better understanding.
        //It can be written Inline as well. (  ex. var result = someCollection.Where(someItem => someItem.Name == "some string").ToList();  )
        //Using Lambda, query against the list of textboxes to see if any of them already contain the same string. If so, return true.
        return textBoxes.AsQueryable()                  //Convert the IEnumerable collection to an IQueryable
            .Any(                                       //Returns true if the collection contains an element that meets the following condition.
                textBoxRef => textBoxRef                //The => operator separates the parameters to the method from it's statements in the method's body.
                                                        //      (Word for word - See http://www.dotnetperls.com/lambda for a better explanation)
                    .Text.ToLower() == str.ToLower()    //Check to see if the textBox.Text property matches the string parameter
                                                        //      (We convert both to lowercase because the ASCII character 'A' is not the same as the ASCII character 'a')
                );                                      //Closes the ANY() statement
    }
} 

要使用它,你可以这样做:

//Initialize list of textboxes with test data for demonstration
List<TextBox> textBoxes = new List<TextBox>();
for (int i = 0; i < 12; i++)
{
     //Initialize a textbox with a unique name and text data.
     textBoxes.Add(new TextBox() { Name = "tbField" + i, Text = "Some Text " + i });
}
string newValue = "some value";
if (textBoxes.IsDuplicateText(newValue) == true) //String already exists
{ 
     //Do something
}
else
{
     //Do something else
}