简体   繁体   中英

How to fix 'combobox selected index always displaying the first value C#'

I have a windows form app that on load fills up my combobox with the data from mysql. But on load I need to hava an empty value first and not selecting the very first from the combobox.

I have tried combobox.SelectedIndex = -1 ; It works but I used a message prompt to debug and I can see that the message displays the first value from the combobox before displaying none.

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

I need to get the message Candidate ID : none on the else if statement. Because I have been getting the Candidate ID for the first item on the combobox.

A common pattern to solve this it to remove the event handler when you are setting up/initializing your controls and add the event handler after initialization.

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

after setting the datasource for your cbo_President object, insert a blank option at position 0 and just do SelectedIndex = 0 . ie.

cbo_President.ValueMember = "candidate_nu";
cbo_President.DisplayMember = "fullname"; 
cbo_President.DataSource = tb;
cbo_President.Items.Insert(0, "No Selection");
cbo_President.SelectedIndex = 0;

You can add an "empty" row to your DataTable before binding it to combobox:

DataRow dr = tb.NewRow();
dr["candidate_nu"] = -1;
dr["fullname"] = string.Empty; // or "No Selection"

tb.Rows.InsertAt(dr, 0);

cbo_President.ValueMember = "candidate_nu";
cbo_President.DisplayMember = "fullname";
cbo_President.DataSource = tb;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM