retrieve data from SQL server depending on value of combo box in datagridview in c# -


i trying retrieve data column in sql db depending on value of combo box in datagridview code :

 private void datagridview1_cellendedit(object sender, datagridviewcelleventargs   {         using (sqlconnection conn = new sqlconnection("data source=posserver\\sqlexpress;initial catalog=ms;integrated security=true"))         {             string priceselected = ("select price table_1 name=" + datagridview1.currentrow.cells[0].value.tostring());             sqlcommand cmd = new sqlcommand(priceselected, conn);             conn.open();             cmd.executenonquery();             conn.close();         }  }  

i want put price in datagridview1.currentrow.cells[2]

but sqlexception everytime choose item combo box

any ??

if data type of column name varchar, need wrap value single quotes because it's string literal.

string _val = datagridview1.currentrow.cells[0].value.tostring(); string priceselected = ("select price table_1 name='" + _val + "'"); 

but query vulnerable sql injection. please parameterized query,eg.

string _val = datagridview1.currentrow.cells[0].value.tostring(); string priceselected = ("select price table_1 name=@val"); sqlcommand cmd = new sqlcommand(priceselected, conn); cmd.parameters.addwithvalue("@val", _val); conn.open(); cmd.executenonquery(); 

Comments