0
votes

Two ComboBoxes - cmbSupplier and cmbProduct

I want to fill cmbSupplier with supplier names from a table

when I select a value from cmbSupplier depending on the name selected Products with the supplier name should fill cmbProduct

private void frmAddOrder_Load(object sender, EventArgs e) {

        SqlCommand cmd = new SqlCommand("SELECT sup_name from tbl_supplier",con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();

        while(dr.Read())
        {
            cmbSupplier.Items.Add(dr["sup_name"].ToString());
        }
        dr.Close();




    }

this is the code I use to fill cmbSupplier

I tried using this code to fill cmbProducts but all I get is an error

         private void cmbSupplier_SelectedIndexChanged(object sender, EventArgs e)
    {


        SqlCommand cmd = new SqlCommand("SELECT Product_Name from tbl_SupplierItems WHERE supplier_name'" + cmbSupplier.Text + "%'", con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();


        while(dr.Read())
        {
            cmbProduct.Items.Add(dr["Product_Name"].ToString());
        }
        dr.Close();



    }
1
Please, provide relevant codeDmitry Bychenko
You would do that with the IndexChanged event on the first combo box. If you want more detailed help you need to provide a LOT more details in your question.Sean Lange
i update the content of my question I'm sorry if its quite messyJosh
Before you write another line of code you need to read about, understand and start using parameterized queries. Your code is wide open to sql injection. bobby-tables.com You also should learn about the USING clause. Use it around all your IDisposable objects like connections and commands.Sean Lange
What you have seems to be reasonably close. But you probably want to add cmdProduct.Items.Clear() before you add the new ones. You said you are "getting an error". If you share the error message it would help others to know what the problem is.Sean Lange

1 Answers

-1
votes

The query is not correct. Instead of

SqlCommand cmd = new SqlCommand("SELECT Product_Name from tbl_SupplierItems WHERE supplier_name'" + cmbSupplier.Text + "%'", con);

You should write

SqlCommand cmd = new SqlCommand("SELECT Product_Name from tbl_SupplierItems WHERE supplier_name = '" + cmbSupplier.Text + "%'", con);