2014-03-03 37 views
0

我想在文本框數組中找到特定的文本框,並返回它的索引。ASP.NET/C# - 在數組中查找條目並獲取索引

該行認爲相關的控制:

TextBox tb1 = Array.Find(m_dynamicTextBoxes, element => element.ID == strFieldId); 

我想找到它的指數,AO我可以替換一個類似的這種控制。檢測到錯誤,所以我打算將BorderColor更改爲紅色。

回答

1

使用Array.FindIndex

var index = Array.FindIndex(m_dynamicTextBoxes, element => element.ID == strFieldId); 

如果你只是想改變BackColor那麼你可以使用你的查詢,並改變顏色在你發現文本框

tb1.BackColor = Color.Red; 
+0

這樣做的竅門。 –

0

簡單LINQ擴展:

​​

或者你可以寫一個類似的擴展名來做t他就地更換並退回被替換的物品:

public static T Replace<T>(this T[] list , Func<T,bool> isDesired , T replacement) where T:class 
{ 
    T replacedItem = null ; 
    for (int i = 0 ; replacedItem == null && i < list.Length ; ++i) 
    { 
    T item = list[i] ; 
    bool desired = isDesired(item) ; 
    if (desired) 
    { 
     replacedItem = item ; 
     list[i]  = replacement ; 
    } 
    } 
    return replacedItem ; // the replaced item or null if no replacements were made. 
} 
+0

兩者都非常有用 - 謝謝。 –