C# show MessageBox 基于Combobox SelectedText

C# show MessageBox based on Combobox SelectedText

如何根据 Combobox 中的各种 SelectedText 显示消息框?当前 return 在 运行ning 时它只是一个 NULL 值。

我需要为每个组合框文本显示特定的消息框,因为我可以这样做,然后根据 SelectedText 不同 SQL 将使用连接和查询 运行。

我在下面包含了我的代码。经过一些研究,似乎 SelectedText 控件在失去焦点时总是 return 空值。我该如何解决这个问题?

private void button2_Click(object sender, EventArgs e)
    {
       if(comboSelectServer.SelectedText == "SERV1")
        {
            MessageBox.Show("SERV1");
        }
       else if(comboSelectServer.SelectedText == "SERV2")
        {
            MessageBox.Show("SERV2");
        }
       else if(comboSelectServer.SelectedText == "SERV3")
        {
            MessageBox.Show("SERV3");
        }
    }
Try like this

private void button2_Click(object sender, EventArgs e)
{
   if(comboSelectServer.SelectedItem.ToString()== "SERV1")
    {
        MessageBox.Show("SERV1");
    }
   else if(comboSelectServer.SelectedItem.ToString()== "SERV2")
    {
        MessageBox.Show("SERV2");
    }
   else if(comboSelectServer.SelectedItem.ToString()== "SERV3")
    {
        MessageBox.Show("SERV3");
    }
}

试试这个。

if (comboSelectServer.Text == "SERV1")
{
    MessageBox.Show("SERV1");
}
else if (comboSelectServer.Text == "SERV2")
{
    MessageBox.Show("SERV2");
}
else if (comboSelectServer.Text == "SERV3")
{
    MessageBox.Show("SERV3");
}

然而,这更容易...

if (comboSelectServer.SelectedIndex == 0) //SERV1
{
    MessageBox.Show("SERV1");
}
else if (comboSelectServer.SelectedIndex == 1) //SERV2
{
    MessageBox.Show("SERV2");
}
else if (comboSelectServer.SelectedIndex == 2) //SERV3
{
    MessageBox.Show("SERV3");
}

也许我遗漏了什么,但为什么不简单地做:

private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show(comboSelectServer.SelectedItem.ToString());
}