Click here to Skip to main content
15,667,422 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
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.
Updated 4-Aug-22 9:15am

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.
Share this answer
string sql = ("SELECT * FROM Customer WHERE (FirstName LIKE \'%" + (txtSearch.Text + "%\')"));
Share this answer
string query = "SELECT * FROM Product WHERE Name LIKE '%" + txt_SearchBar.Text + "%' OR ID LIKE '%" + txt_SearchBar.Text + "%'";
Share this answer
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.
string query = "SELECT * FROM UsersTable WHERE Correo_Electronico LIKE '%" + infoBuscada + "%' OR Documento LIKE '%" + infoBuscada + "%' OR Nombre LIKE '%" + infoBuscada + "%' OR Rol LIKE '%" + infoBuscada + "%'OR Usuario LIKE '%" + infoBuscada + "%'";
Share this answer
Richard Deeming 5-Aug-22 9:08am    
This question was solved 10 years ago. A new solution adding a SQL Injection[^] vulnerability which wasn't present in the question is NOT a good reason for resurrecting this thread!

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