I am getting error on this line: using (SqlDataReader reader =cmd.ExecuteReader())
I am working on AJAX cascading Drop Down Example in ASP.Net and below is my code. I am unable to run the code due to error
Incorrect syntax near '='. near using (SqlDataReader reader =cmd.ExecuteReader())
Code
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownCountry1(string knownCategoryValues)
{
// select CountryId, Country from Country where Status='Active'
// string query = "SELECT Country, CountryId FROM Country";
string query = "select [CountryName], [CountryId] from 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] FROM Cities where StateId = {0}", state);
If state is a string like "CA" then this will generate the SQL statement "select [CityName], [CityId] FROM Cities where StateId = CA", which is not valid. Values passed as strings need to be quoted. But don't just put quotes around "{0}" - the correct fix is to use a parametrized query and pass the StateId as a parameter. Something like:
string sql = "select [CityName], [CityId] FROM Cities where StateId = @stateId"
cmd.Parameters.Add("stateId", stateId);
This is more efficient and protects you from SQL injection .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.