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

我只是一个虾纸丫 提交于 2019-12-13 05:26:47

问题


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.


回答1:


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 ;



回答2:


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!



来源:https://stackoverflow.com/questions/34438423/how-to-use-the-selected-value-in-combobox-to-the-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!