首页 > 解决方案 > 如何修复“组合框选定索引始终显示第一个值 C#”

问题描述

我有一个 Windows 窗体应用程序,它在加载时会用来自 mysql 的数据填充我的组合框。但是在加载时,我需要先有一个空值,而不是从组合框中选择第一个。

我试过了combobox.SelectedIndex = -1;它可以工作,但我使用消息提示进行调试,我可以看到该消息显示组合框中的第一个值,然后再显示无。

void Fillcombo()
{
    DataTable tb = new DataTable("candidate_l");
    connection.Open();
    string QueryPres = "SELECT candidate_nu, CONCAT(candidate_n, ' ' ,candidate_s) AS fullname FROM candidate_l WHERE candidate_p = 'PRES'";
    cmd = new MySqlCommand(QueryPres, connection);
    mdr = cmd.ExecuteReader();

    tb.Load(mdr);

    cbo_President.ValueMember = "candidate_nu";
    cbo_President.DisplayMember = "fullname";
    cbo_President.DataSource = tb;
    cbo_President.SelectedIndex = -1;
    cbo_President.Text = "No Selection";

    connection.Close();
}

private void cbo_President_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cbo_President.SelectedIndex > -1)
    {
        string cbopres = cbo_President.SelectedValue.ToString();
        MessageBox.Show("Candidate ID : " + cbopres);
    }
    else if (cbo_President.SelectedIndex == -1)
    {
        MessageBox.Show("Candidate ID : none");
    }
}

我需要Candidate ID : none在 else if 语句中得到消息。因为我一直在获得Candidate ID组合框中的第一项。

标签: c#

解决方案


解决此问题的常见模式是在设置/初始化控件时删除事件处理程序并在初始化后添加事件处理程序。

        comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
        comboBox1.DataSource = test;
        comboBox1.SelectedIndex = -1;
        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

推荐阅读