简体   繁体   中英

The selectedIndexChanged is auto triggered without selecting items in combobox in c# windows application

I have a combo box which is populated from database.The code is as below

protected void bindcombobox()
    {
        string str = "Data Source=IMMENSE-01\\SQLEXPRESS;Initial Catalog=DesktopAppDB;Integrated Security=True;Pooling=False";
        SqlConnection con = new SqlConnection(str);
        con.Open();
        SqlCommand cmd = new SqlCommand("select Id,designation from addStaff", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();

        da.Fill(ds);
        da.Fill(dt);
        cb_selectpost.Items.Clear();
        if (dt.Rows.Count > 0)
        {

            cb_selectpost.DataSource = dt;
            cb_selectpost.ValueMember = "Id";
            cb_selectpost.DisplayMember = "designation";


        }
        con.Close();
        con.Dispose();
    }

I have this event which gets triggered on selecting item from combobox as

 private void cb_selectpost_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cb_selectpost.SelectedValue != null)
        {
            string st = cb_selectpost.SelectedValue.ToString();
            lblCB.Text = st.ToString();
            bindstaff(st);
        }
    }

But the problem is that this event is auto triggered on runnning the project without letting me to select item from combobox.

You can either subscribe to SelectionChangeCommitted event instead of SelectedIndexChanged event. or you can unsubscribe to SelectedIndexChanged event before data laods, and subscribe it after data is loaded into combo box. You can solve this issue in multiple ways.

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