【问题标题】:C# show MessageBox based on Combobox SelectedTextC# 基于 Combobox SelectedText 显示 MessageBox
【发布时间】:2018-10-06 23:06:29
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你可以试试SelectedIndex而不是SelectedText
  • @defaultlocale 没有回答我的问题。我需要根据组合框中选择的文本显示特定的消息框,这就是我使用的原因和 if。一旦我破解了这个,那么计划是运行特定的 sql 连接和语句而不是消息框
  • @WHoward 听起来是个很棒的计划!但是现在,你在问,我引用:SelectedText control will always return a null value as it loses focus. How do I get around this? 这个问题已经在这里被问过并得到了回答。您可能想先解决 SelectedText 的问题,然后继续进行项目的其余部分。
  • @defaultlocale 感谢您的帮助,使用 SelectedIndex 对所有内容进行了排序

标签: c# winforms combobox messagebox selectedtext


【解决方案1】:

试试这个。

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

【讨论】:

  • 我尝试了第二个选项,但将 ' 标记保留在 0,1,2.. 周围,我真傻!谢谢你告诉我正确的方法
【解决方案2】:
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");
    }
}

【讨论】:

    【解决方案3】:

    也许我错过了什么,但为什么不干脆做:

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

    【讨论】:

      猜你喜欢
      • 2011-07-23
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多