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

时间:2014-11-06 20:46:34

标签: c#

我有12个文本框,我试图找到一个策略,允许用户在运行时不允许TextBox中的重复条目。

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");
    }
}

2 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分: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
}