this is my select query with where clause every time I call it the datatable is empty and list count is 0 please correct my select query or ado.net code. I want to get data from the SQL server from these parameters but I don’t know my SQL query is wrong or the ado.net code is wrong
public List<AdsModel> GetAds(string _location, Int64 _maxprice, Int64 _minprice, int _maxarea, int _minarea)
{
connection();
List<AdsModel> AdsModelList = new List<AdsModel>();
SqlCommand cmd = new SqlCommand("select * from propertydata_tbl where Location like '%@location%' and Price >= @minprice and Price <= @maxprice and Area >= @minarea and Area <= @maxarea", con);
cmd.Parameters.AddWithValue("@location", _location);
cmd.Parameters.AddWithValue("@minprice", _minprice);
cmd.Parameters.AddWithValue("@maxprice", _maxprice);
cmd.Parameters.AddWithValue("@minarea", _minarea);
cmd.Parameters.AddWithValue("@maxarea", _maxarea);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
AdsModelList.Add(
new AdsModel
{
id = Convert.ToInt32(dr["Id"]),
price = Convert.ToInt64(dr["Price"]),
location = Convert.ToString(dr["Location"]),
area = Convert.ToInt32(dr["Area"]),
postdate = Convert.ToString(dr["Postdate"]),
titlelink = Convert.ToString(dr["Titleline"]),
adlink = Convert.ToString(dr["Adlink"])
}
);
}
}
return AdsModelList;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
ADO doesn’t interpolate strings, and regards everything inside single quotes as a string literal sent to SQL. You should extract the @location from this literal:
SqlCommand cmd = new SqlCommand("select * from propertydata_tbl where Location like '%' + @location + '%' and Price >= @minprice and Price <= @maxprice and Area >= @minarea and Area <= @maxarea", con);
// Here --------------------------------------------------------------------------------^-----------^
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0