Click here to Skip to main content
14,970,229 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi everyone ,
I am trying to write a query in C# to search in the sql table.
the sql query
SQL
SELECT *
FROM Customer
WHERE FirstName LIKE '%34%'
or LastName LIKE '%Appiah%'
Or State LIKE '%OH%';



in C# i want it to search for what inside the textbox .
ex. LIKE %textBox.text%
but i don't know how to write it.
Posted
Updated 22-May-21 21:27pm
v2

If you are looking at using LINQ (which would be used with EntityFramework), then would want to use something like string.Contains. Using extension methods with LINQ:

var x = Customer.Where(i => i.FirstName.Contains(x) || i.LastName.Contains(y) || i.State.Contains(z))


If you want exact matches then would use the equal "==" operator instead. Can also created a RegEx expression. As stated above, using SQL statement directly is generally frowned upon because of SQL injection.

What might be another option is to create a SQL proceedure that takes the arguments for FirstName, LastName, and State, and returns those records matching the request.
   
v2
string sql = ("SELECT * FROM Customer WHERE (FirstName LIKE \'%" + (txtSearch.Text + "%\')"));
   
string query = "SELECT * FROM Product WHERE Name LIKE '%" + txt_SearchBar.Text + "%' OR ID LIKE '%" + txt_SearchBar.Text + "%'";
   
Comments
Richard MacCutchan 23-May-21 4:10am
   
Already answered nine years ago.
Tony Hill 23-May-21 6:17am
   
As Richard said this question was answered nine years and your solution is vulnerable to SQL injection attacks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900