Reputation: 33
public DataTable Search()
{
DataTable dt = new DataTable();
SqlCommand searchcommand = new SqlCommand(
"Select * from [ITEM MASTER] WHERE Item_Description LIKE '%' @Item_Description '%' ", con);
searchcommand.Parameters.Add("@Item_Description", SqlDbType.NVarChar).Value = search;
SqlDataAdapter da = new SqlDataAdapter(searchcommand);
da.Fill(dt);
return dt;
}
Here is my code. I need help on how to create a parameterized search using Object Oriented Programming
Upvotes: 3
Views: 119
Reputation: 141462
As Nathan said, just add +
on either side of the @Item_Description
parameter. This will concatenate it together with the rest of the command string.
SqlCommand searchcommand = new SqlCommand("Select * from [ITEM MASTER] WHERE Item_Description LIKE '%' + @Item_Description + '%' ", con);
If you want to make your code slightly more readable, you can use the @
to make a verbatim string. Among other things, the verbatim string lets us put a string onto multiple lines, like this:
SqlCommand searchcommand = new SqlCommand(
@"Select *
from [ITEM MASTER]
WHERE Item_Description
LIKE '%' + @Item_Description + '%' ", con);
For even more readability, you can put your string into its own variable, put the T-SQL keywords into all caps, and add a semicolon at the end of the command text, which would look like this...
var commandText = @"
SELECT *
FROM [ITEM MASTER]
WHERE Item_Description
LIKE '%' + @Item_Description + '%';
";
SqlCommand searchcommand = new SqlCommand(commandText, con);
That's much nicer to read, in my opinion, when you next come across it in your maintenance work.
Upvotes: 2