【问题标题】:C# Changing Label Text to Listbox Selection TextC# 将标签文本更改为列表框选择文本
【发布时间】:2015-11-07 23:21:07
【问题描述】:

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

这是我之前认为可以工作的代码行:

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

但有一次它没有改变,另一个代码块变成了“0”。使用“ToString”时,有时也会出现空错误。

谢谢, 威廉

【问题讨论】:

    标签: c# text listbox label


    【解决方案1】:

    试试这个:

    private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e)
            {
    
    if(instanceSelection.SelectedIndex > -1)
         instanceTxt.Text = instanceSelection.Items[instanceSelection.SelectedIndex].ToString();
            }
    

    【讨论】:

    • 你能解释一下为什么会这样吗?如,为什么条件为-1?我不明白这个...
    • 当然。有时它给出 -1 值。所以我设置了一个 if 条件来检查以防止 indexoutofbound 异常。
    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多