2014-11-06 55 views
-2

我有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"); 
    } 
} 
+0

是那些認爲哪些事件是:'私人無效Textbox1'?您還將文本添加到列表中,*然後*檢查列表是否包含該項目,它確實會這樣做。 – LarsTech 2014-11-06 20:49:42

+0

把你的'TextBox's放入一個'List '將會使這容易很多 – Jonesopolis 2014-11-06 20:51:56

+1

你的'List '將會無限增長。你應該使用'詞典'無論如何 – 2014-11-06 20:52:54

回答

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

請解釋x和g的作用是什麼? – 2014-11-06 21:16:08

+0

簡單地說,想象一個foreach循環......'foreach(var textBoxes)','x'指向循環中的每個項目。你可以將它改爲任何你喜歡的東西,例如:'(item => item.Text)'。查看'lambda表達式'來理解實際發生的事情。 – learningcs 2014-11-06 21:23:58

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 
}