2015-11-07 138 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