c# - WebMethod throws "Incorrect syntax near '='" -
i getting error on line: using (sqldatareader reader =cmd.executereader())
i working on ajax cascading drop down example in asp.net , below code. unable run code due error
incorrect syntax near '='. near using (sqldatareader reader =cmd.executereader())
code
[webmethod] public ajaxcontroltoolkit.cascadingdropdownnamevalue[] getdropdowncountry1(string knowncategoryvalues) { // select countryid, country country status='active' // string query = "select country, countryid country"; string query = "select [countryname], [countryid] countries"; list<ajaxcontroltoolkit.cascadingdropdownnamevalue> countries = getdata(query); return countries.toarray(); } private list<ajaxcontroltoolkit.cascadingdropdownnamevalue> getdata(string query) { string constring = configurationmanager.connectionstrings["connectionstring"].connectionstring; sqlcommand cmd = new sqlcommand(query); list<ajaxcontroltoolkit.cascadingdropdownnamevalue> values = new list<ajaxcontroltoolkit.cascadingdropdownnamevalue>(); using (sqlconnection con = new sqlconnection(constring)) { con.open(); cmd.connection = con; using (sqldatareader reader = cmd.executereader()) { while (reader.read()) { values.add(new ajaxcontroltoolkit.cascadingdropdownnamevalue { name = reader[0].tostring(), value = reader[1].tostring() }); } reader.close(); con.close(); return values; } } }
string state = ajaxcontroltoolkit.cascadingdropdown.parseknowncategoryvaluesstring(knowncategoryvalues)["stateid"]; string query = string.format("select [cityname], [cityid] cities stateid = {0}", state);
if state string "ca" generate sql statement "select [cityname], [cityid] cities stateid = ca", not valid. values passed strings need quoted. don't put quotes around "{0}" - correct fix use parametrized query , pass stateid parameter. like:
string sql = "select [cityname], [cityid] cities stateid = @stateid" cmd.parameters.add("stateid", stateid);
this more efficient , protects sql injection.
Comments
Post a Comment