【发布时间】:2018-12-03 14:09:06
【问题描述】:
我正在使用 SQL Server 数据库,我有一个包含多列的表 ([First Name], [Last Name]),我在 datagridview 中显示它。我的 UI 中还有一个文本框 (txtBoxSearch)。如何仅使用 1 个字符串在两列中进行搜索?
我在导航到用户屏幕时调用此方法以加载 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");
}
}
这是我的代码,它适用于第一次搜索,但再次搜索后它会显示找不到记录。
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();
}
}
【问题讨论】:
-
“什么都不显示”是什么意思?
-
对我来说看起来不错(减去使用
SELECT *但我离题了)。你能发布更多代码吗? -
上面的SQL应该一直搜索相同的,每次。所以你周围的代码有问题
标签: c# sql sql-server