C# show MessageBox based on Combobox SelectedText

125 Views Asked by At

How do I show a messagebox based on the various SelectedText in the Combobox? It currently just returns a NULL value when running.

I need to show the specific messagebox for each Combobox Text as once I can do this then depending on the SelectedText different SQL Connections will be used and Queries run.

I've included my code below. After some research it seems that the SelectedText control will always return a null value as it loses focus. How do I get around this?

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");
        }
    }
3

There are 3 best solutions below

1
DxTx On BEST ANSWER

Try this.

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

However, this is easier...

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");
}
0
Rajeswari Renganathan On
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");
    }
}
0
Luc Morin On

Maybe I'm missing something, but why not simply do:

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