How can I use Parameters.AddWithValue with an SqlDataAdapter. Below searching codes.
var da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%"+txtSearch.Text+"%'", _mssqlCon.connection);
var dt = new DataTable();
da.Fill(dt);
I rewrote the code like this:
SqlDataAdapter da;
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%@search%'", _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("@search",txtSearch.Text);
var dt = new DataTable();
da.Fill(dt);
but it failed.
The string used to initialize the SqlDataAdapter becomes the value for the
CommandTextproperty inside the SelectCommand property of the SqlDataAdapter.You could add parameters to that command with this code
AddWithValue
You have asked to use AddWithValue, but remember that, while it is a useful shortcut, there are also numerous drawbacks and all well documented.
author discuss how AddWithValue could be the source for wrong results in your
queries
the author presents evidences of strong performance problems for
AddWithValue
So, the same code without AddWithValue and using the Object and Collection Initializers syntax could be written as
and, an even more simplified and one liner version of the above is: