Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey,
I'm trying to use 2 comboboxes that all reads data from different sql table. I need to do that;
-When i select something on combobox1 (it only reads names on a Column)
-when i want to select something on combobox 2(it only reads Surnames on a Column in different table), i want to see names that starts with name on combobox1.



here is my code;

C#
SqlConnection con1 = new SqlConnection("Data Source=.;Initial Catalog=AY_DB;Integrated Security=True");
con1.Open();
SqlCommand cmd2 = new SqlCommand("select Name from CLASS", con1);
SqlCommand cmd3 = new SqlCommand("select Surname from CLASS2 where (Name = '" + comboBox1.Text + "')", con1);
SqlDataReader dr1,dr2;

try
{
    dr1 = cmd2.ExecuteReader();

    while (dr1.Read())
    {

        comboBox1.Items.Add(dr1["Name"]);

    }
    con1.Close();

}
catch (Exception es)
{
    MessageBox.Show(es.Message, "FAIL");
}
try
{
    con1.Open();
    dr5 = cmd3.ExecuteReader();
    while(dr2.Read())
    {
        comboBox2.Items.Add(dr5["Surname"]);
    }
    con1.Close();
}

    catch(Exception eg)
{
        MessageBox.Show(eg.Message,"FAIL");

    }



Names in CLASS table is as same as in CLASS2 table and their table names are same too(both column names are "name"). I can see names on combobox1. It's ok but, after selecting an item on combobox1, i couldn't see an item on combobox2. It seems empty.
How can i see surnames which starts with item on combobox1?
Posted
Comments
Richard Deeming 12-Jan-15 9:59am    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

XML
you should subscribe to combobox event SelectedValueChanged
And if the Event fired , do you select with cmd3 and refill the combobox2with new data

See for example HERE
<a href="http://msdn.microsoft.com/de-de/library/system.windows.forms.listcontrol.selectedvaluechanged(v=vs.110).aspx">http://msdn.microsoft.com/de-de/library/system.windows.forms.listcontrol.selectedvaluechanged(v=vs.110).aspx</a>
 
Share this answer
 
As already pointed out, you need to handle the SelectedIndexChanged[^] event in the first combo and in that event you fill the second combo. So basically you split your code to two different places.

Also it's important to notice that because you concatenate values directly to your SQL statement, you're vulnerable to different kinds of problems such as SQL injection, data type conversion problems and so on. The proper way is to use parameters as explained in SqlParameter[^]
 
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