listBox中的switch语句

时间:2014-05-11 18:03:42

标签: c# windows-forms-designer

如果我使用 listBox ,如何在我的情况下使用开关语句?

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox2.GetSelected(0))
                richTextBox1.Text = "0";
            else if (listBox2.GetSelected(1))
                richTextBox1.Text = "1";

        }

2 个答案:

答案 0 :(得分:1)

switch (listBox2.SelectedIndex)
{
    case 0:
        richTextBox1.Text = "0";
        break;
    case 1:
        richTextBox1.Text = "1";
        break;
}

或者:

richTextBox1.Text = listBox2.SelectedIndex.ToString();

答案 1 :(得分:1)

尝试SelectedItem属性。

switch (listBox2.FindString(listBox2.SelectedItem.ToString()))//find the index of the selected string
{
    case 0:
        richTextBox1.Text = "0";
        break;
    ...
}

虽然,打电话

会更有效
//Do the same as above, then convert to string
richTextBox1.Text = listBox2.FindString(listBox2.SelectedItem.ToString()).ToString();

当它获取所选项目时,查找其索引,然后将索引转换为字符串。