2015-11-07 137 views
1

所以我一直在瀏覽谷歌的偉大思想,但還沒有找到一個工作的解決方案,我有一個列表框(instanceSelection)和一個標籤(instanceTxt)。當我選擇集合中的一個項目時,我希望instanceTxt與instanceSelection的文本相同。C#將標籤文本更改爲列表框選擇文本

這裏是我認爲會的早期工作的代碼行:

private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     instanceTxt.Text = (string)this.instanceSelection.SelectedValue.Text; 
    } 

但在同一時間並沒有改變,而另一個代碼塊把它改爲「0」。使用「ToString」時,我有時也會得到一個空錯誤。

感謝, 威廉

回答

1

試試這個:

private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e) 
     { 

if(instanceSelection.SelectedIndex > -1) 
    instanceTxt.Text = instanceSelection.Items[instanceSelection.SelectedIndex].ToString(); 
     } 
+0

你能解釋爲什麼這個工作?如在,爲什麼條件爲-1?我不明白這個...... – SkyeRangerDelta

+0

當然。有時它給-1值。所以我把一個if條件來檢查,以防止indexoutofbound異常。 – TdSoft