I am using a SQL Server database, I have a table with multiple columns ([First Name], [Last Name]
), I display it in the datagridview. I also have a single textbox (txtBoxSearch
) in my UI. How can I search in two columns using only 1 string?
I call this method when navigated to the user screen to load the the data in the datagridview:
private void LoadData() {
try {
string sqlCommand = "SELECT * from tbl_user";
con = new SqlConnection(connectionString);
dataAdapter = new SqlDataAdapter(sqlCommand, connectionString);
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dataGridProducts.DataSource = table;
} catch (Exception ex) {
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message), "Error");
}
}
This is my code, it works for the first search, but after searching again it will show no record found.
if (!string.IsNullOrWhiteSpace(txtBoxSearch.Text)) {
try {
using (SqlConnection con = new SqlConnection(connectionString)) {
con.Open();
string sqlCommand = "SELECT * FROM tbl_user WHERE CONCAT([First Name], [Last Name]) LIKE '%" + txtBoxSearch.Text + "%'";
using (SqlCommand cmd = new SqlCommand(sqlCommand, con)) {
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(dt);
if (dt.Rows.Count > 0) {
dataGridProducts.DataSource = dt;
} else {
MessageBox.Show("No record found.", "Error");
}
}
}
} catch (Exception ex) {
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message), "Error");
} finally {
con.Close();
}
}