我正在使用 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();
}
}
最佳答案
我在这里看到的几个问题。我模拟了您的简单表格,并运行了下面的代码,它工作得很好。
string sqlCommand = "SELECT [Fist Name], [Last Name] FROM tbl_user WHERE [First Name] LIKE '%" +
txtBoxSearch.Text + "%' OR [Last Name] LIKE '%" + txtBoxSearch.Text + "%'";
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
using(var dataAdapter = new SqlDataAdapter(sqlCommand, connectionString))
{
dataAdapter.Fill(table);
}
dataGridUser.DataSource = table;
据我所知,您不需要SqlCommandBuilder
。您也不需要 BindingSource
也不需要使用它。
我在这里所做的唯一区别是处理dataAdapter
。
例如,上面的代码在单击按钮时工作得很好。
我怀疑您没有发布所有代码。如果可能的话,请发布可以完全重现该问题的代码。
关于c# - 如何使用单个文本框搜索多列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51016027/