Chelsea
Chelsea

Reputation: 751

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.

Upvotes: 0

Views: 568

Answers (1)

Niranjan Reddy
Niranjan Reddy

Reputation: 94

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.

Upvotes: 2

Related Questions