Quantcast
Channel: DataSource Controls - SqlDataSource, ObjectDataSource, etc.
Viewing all articles
Browse latest Browse all 956

can't get cmd.Parameters.AddWithValue to work

$
0
0

HI

I have a web service that fetches image names matching user input text in an autocomplete text box.  The code below works but has a flaw - the SearchText is user input and I want to avoid SQL injection attacks.

List<string> my_list = new List<string>();
string conString = ConfigurationManager.ConnectionStrings["Images_Connection"].ConnectionString;
string query = "Select TOP (@Count) image_Name FROM dbo.Table_Images WHERE (image_Name LIKE '%@SearchText%')";
query = query.Replace("@Count", count.ToString());
query = query.Replace("@SearchText", prefixText);
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);

DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
sqlConn.Close();
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
my_list.Add(row[0].ToString());
}
}
return my_list;

If I update the code to update the parameter @SearchText (as follows), even though I enter the same text, nothing is returned. 

string query = "Select TOP (@Count) image_Name FROM dbo.Table_Images WHERE (image_Name LIKE '%@SearchText%')";
query = query.Replace("@Count", count.ToString());
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
//https://forums.asp.net/t/1132244.aspx
cmd.Parameters.AddWithValue("@SearchText", prefixText);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
sqlConn.Close();

What am I doing incorrectly?

Thanks for any help.


Viewing all articles
Browse latest Browse all 956

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>