Long Nguyen
Long Nguyen

Reputation: 1

How to use the selected value in ComboBox to the SQL query?

When I choose a value in ComboBox. How can I use them to query SQL??

I tried

private void cmb1_SelectedIndexChanged(object sender, EventArgs e)
{
   string select = this.cmb1.GetItemText(this.cmb1.SelectedItem);
   cm1 = new SqlCommand("select VS from DATABASE where ROUND=select", con);
   ap = new SqlDataAdapter(cm1);
   ds = new System.Data.DataSet();
   ap.Fill(ds, "DATABASE");
   cmb2.DataSource = ds.Tables[0]; 
   cmb2.DisplayMember = "VS"; // show in combobox2
}

I want to use the variable select to query but it doesn't work.

Upvotes: 0

Views: 3156

Answers (2)

ohiodoug
ohiodoug

Reputation: 1513

You want to be careful with simply injecting values into your SQL. If you're going to use ADO like this, I'd recommend parameters.

cm1 = new SqlCommand("select VS from DATABASE where ROUND=@ROUND", con);
cm1.Parameters.Add("@ROUND", SqlDbType.VarChar);
cm1.Parameters["@ROUND"].Value = select;
  • Note - I saw vantian beat me to this answer so I'll try to explain a bit more about why you should use the parameters.

When you use include values posted from a web app (or API or any application where a user can define those values) you can't simply put it inline into your SQL query. A savvy, or a**hole, user can inject their own SQL into their value and your application won't know the difference and run it. With this power, a user can do whatever they want to your data -- such as steal it, or if you're lucky, only delete it to mess with your operations.

The parameters will automatically "cleanse" your input by wrapping the proper quotes and such around it and you will have a far more secure application.

Good luck!

Upvotes: 0

vantian
vantian

Reputation: 888

You need to pass your select to sql parameter

string select = this.cmb1.GetItemText(this.cmb1.SelectedItem);
cm1 = new SqlCommand("select VS from DATABASE where ROUND=@round", con);
cm1.Parameters.Add("@round", SqlDbType.NVarChar, -1);
cm1.Parameters["@round"].Value = select ;

Upvotes: 2

Related Questions