0

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.

3
  • I don't understand your question. Are cmb2 and combobox2 same? You wanna use selected value in combobox2 as a parameter in your sql query instead? Can you please be more specific? By the way, your where ROUND=select won't work if you try to query select as a text. You need to use where ROUND = 'select' in such a case. Commented Dec 23, 2015 at 15:04
  • Yes, the cmb2 is the ComboBox2, but I want to use the selected value in ComboBox1 as a parameter, not in ComboBox2 Commented Dec 23, 2015 at 15:05
  • select is a terrible name for a variable. Commented Dec 23, 2015 at 15:20

2 Answers 2

2

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 ;
Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.