2016-03-14 36 views
-3

基本上我試圖使它所以如果從列表框中選定的指數(例如可以說選擇的指數是「服務器1」)包含一個數字(「1」)或某些字(「服務器」)它會做某件事。例如:如果從列表框中選擇的索引包含數字1,則會在文本框中輸入1。如果選定的索引包含數字2,它將打開一個應用程序,僅作爲示例。如果ListBox.SelectedIndex包含數字1

我的嘗試:

 if (csrListBox.SelectedIndex = "1"); 

和:

 { 
      List<string> items = ListBox.Items.Cast<string>().ToList(); 
      foreach (string item in ListBox.Items) 
      { 
       Regex regex = new Regex(@"1"); 
       Match match = regex.Match(item); 
       if (match.Success) 
       { 
        *Doing Something* 
       } 
      } 

      ListBox.DataSource = items; 
     } 
+3

'SelectedIndex'is一個int。嘗試'SelectedItem'或'SelectedValue' – Pikoh

+0

'SelectedIndex'是一個int,所以使用'if(csrListBox.SelectedIndex == 1){...}'。我假設你不熟悉C#並且通常使用VB.NET。如果您想比較,請始終使用相同的類型並使用'=='而不是'='。 –

+0

這個問題真的不清楚。如果選定**索引處的**項目包含「1」或某個單詞,您是否嘗試執行您的代碼?或者如果**選擇的索引**本身是1,你想執行代碼嗎? – Louis

回答

2

試試這個: 如果(csrListBox.SelectedIndex == 1);

第二個「=」號的問題 - 它規定你正在做一個布爾檢查,而不是在價值分配值「1」。

+1

'SelectedIndex'是一個int索引。不能等於「1」 – Pikoh

+0

謝謝,發現了一個錯誤,但沒有發現其他錯誤! –

0

錯誤 - 您正在分配價值。

使用比較操作==。並且SelectedIndex是int而不是字符串。

if (csrListBox.SelectedIndex == 1) 
{ 
    // Your code goes here. 
} 
0

我建議你使用ListBox項目值而不是selectedIndex,因爲SelectedIndex只能是一個整數值。如果ListBox包含選定的某個值,則返回類似於此linq查詢的內容。這也照顧多選。

var myValue = "1"; 
bool listContainsItem = ListBox.Items.Any(item => item.Value == myValue && item.Selected);