Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanna select from first combobox id of a train and in the second combobox give me the wagon that train has (number of a wagon ) I did a database: that first table stored the train id and the second table stored wagon id + id train foreign key i tried this code and its work but when i choose another id it doesn't change the wagon combobox result

What I have tried:

C#
adapter = new SqlDataAdapter("select * from train", cn);
            SqlCommand cmd = new SqlCommand("select * from train", cn);
            cmd.Parameters.Clear();
            adapter.Fill(ds, "train");
            
            comboBox1.DataSource = ds.Tables["train"];
            comboBox1.DisplayMember = "id";
            comboBox1.ValueMember = "id";
           
            
       adapter = new SqlDataAdapter("select  id_w  from wagon  where id='" + comboBox1.SelectedValue + "'", cn);
        
            
                adapter.Fill(ds, "wagon");

        //    adapter1.SelectCommand.Parameters.Clear();
            comboBox2.DataSource = ds.Tables["wagon"];
                comboBox2.DisplayMember = "id_w";
                comboBox2.ValueMember = "id_w";
Posted
Updated 25-Feb-18 18:08pm
v2
Comments
Maciej Los 25-Feb-18 15:04pm    
What's your question?
Richard Deeming 26-Feb-18 10:27am    
Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

adapter = new SqlDataAdapter("select id_w from wagon where id = @id", cn);
adapter.SelectCommand.Parameters.AddWithValue("@id", comboBox1.SelectedValue);

1 solution

Hello,
ComboBox.SelectedIndexChanged event occurs when the SelectedIndex property has changed.
You have to pass train_id in train_SelectedIndexChanged event.
i.e.,
private void train_SelectedIndexChanged(object sender,System.EventArgs e)
    {
       //Load the wagon_details and populate in combobox.
    }

thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900