Skip to content
Advertisement

Search bar in C# to search for data where string is equal to value C#

I’ve written a program which includes a datagridview and search bar. The user is required to log in to the software before use and will be shown data related to their unique ID which is stored as a string within the program and the user can only see their own records in the datagridview and nobody else. My search bar works fine functionally but when you delete the text in the datagridview it refreshes and shows all the data in my table rather than just the logged in users data.

This is my code.

SqlDataAdapter sda = new SqlDataAdapter("Select * from Leads where Full_Name like'" + textBox2.Text + "%' or Company like'" + textBox2.Text + "%' where Owner='" + User_ID + "'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "Leads");
dataGridView4.DataSource = ds.Tables[0];

Advertisement

Answer

As others have mentioned, it appears that you have a problem with your SQL statement having two where clauses.

Reformmatted:

SqlDataAdapter sda = new SqlDataAdapter($"Select * from Leads where (Full_Name like '{textBox2.Text}%' or Company like '{textBox2.Text}%') and Owner = '{User_ID}'", con);

The and before Owner could be whatever operator you need depending on your use case.

I also changed the text to use $string interpolation which can look a bit cleaner and easier to read.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement