C# correct syntax in sql string when filtering for a text field from a dropdownlist

I have a gridview and a drop down list. When a selection is made from the list, I want to filter the grid. I need to filter based on the selection from a drop down list. The value selected is a text field. I need the correct syntax for the sql statemtn in the c# code behind. What am I missing?
Here is my sql string. The Comp1 and Comp2 fields are text fields.
 
string strTransactions = "select * FROM vwTransactionsByComp where Comp1 = " + ddlComp.SelectedValue + " OR Comp2 = " + ddlComp.SelectedValue;
dodgerfanAsked:
Who is Participating?
 
käµfm³d 👽Commented:
You are using string concatenation to build queries. This is bad. I would suggest using parameterized queries. For example:

using (SqlConnection con = new SqlConnection("your connection string"))
{
    using (SqlCommand cmd = new SqlCommand("select * FROM vwTransactionsByComp where Comp1 = @searchVal OR Comp2 = @searchVal", con))
    {
        try
        {
            con.Open();
            cmd.Parameters.Add("@searchVal", ddlComp.SelectedValue);
            SqlDataReader reader = cmd.ExecuteReader();
        }
        catch (SqlException ex)
        {
            // log exception
        }
    }
}

Open in new window


Hopefully you can see that query is now a bit easier to read on top of being a bit safer to actually send to the database.

Note:  I am using a reader in the above, but that is only for example. You would need to tweak that code to fit your environment.
0
 
käµfm³d 👽Commented:
P.S.

The reason your previous code doesn't work is because you are trying to test textual columns and you didn't quote the incoming values within your query (i.e. wrap the value that's coming from the combo box in single quotes). However, I still recommend you consider using what I described above.
0
 
dodgerfanAuthor Commented:
Got it. Thanks for the help and tips.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.