有很多方法可以做到這一點。我選擇了將解決方案作爲擴展方法提供,但只需將該方法放入包含文本框列表的類中或將該列表作爲參數傳遞即可獲得相同的結果。你喜歡哪一個。
將以下內容剪切並粘貼到您的項目中。確保將其放在同一個名稱空間中,否則,將包含的名稱空間添加爲參考。
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
}
是那些認爲哪些事件是:'私人無效Textbox1'?您還將文本添加到列表中,*然後*檢查列表是否包含該項目,它確實會這樣做。 – LarsTech 2014-11-06 20:49:42
把你的'TextBox's放入一個'List'將會使這容易很多 –
Jonesopolis
2014-11-06 20:51:56
你的'List'將會無限增長。你應該使用'詞典'無論如何 –
2014-11-06 20:52:54