How to use Wildcard Search Parameterized?

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

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141462

Short Answer

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);

More Advice

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...

Final Code Sample

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

Related Questions