C#将标签文本更改为列表框选择文本

C#将标签文本更改为列表框选择文本,c#,text,listbox,label,C#,Text,Listbox,Label,所以我一直在浏览谷歌的伟大思想,但没有找到一个有效的解决方案;我有一个列表框(instanceSelection)和一个标签(InstanceText)。在集合中选择项目时,我希望InstanceText与instanceSelection的文本相同 下面是我之前认为可以使用的代码行: private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e) { instanceTxt.

所以我一直在浏览谷歌的伟大思想,但没有找到一个有效的解决方案;我有一个列表框(instanceSelection)和一个标签(InstanceText)。在集合中选择项目时,我希望InstanceText与instanceSelection的文本相同

下面是我之前认为可以使用的代码行:

private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e)
    {
        instanceTxt.Text = (string)this.instanceSelection.SelectedValue.Text;
    }
但有一次它没有改变,而另一个代码块则改为“0”。当使用“ToString”时,有时也会出现空错误

谢谢, 威廉试试这个:

private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e)
        {

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

你能解释一下为什么会这样吗?如中所示,为什么条件为-1?我不明白…当然。有时它给出-1值。所以我设置了一个if条件来检查它,以防止indexoutofound异常。