我对编码非常陌生,正尝试通过小项目学习C#。
我花了一个星期或更多的时间来寻找解决方案,但是尽管线程很多,但它们对我来说都不有意义,因此无法正常工作。
我有一个带有DataGridView的窗体,我想创建6个ComboBox对其进行过滤。全部具有相同的数据源。
到目前为止,我设法使DataGridView与一个ComboBox一起使用,但不知道如何添加更多这些。
我的代码:
using System.Data;
using System.Data.SqlClient;
public partial class frmEmpList : Form
{
private void frmEmpList_Load(object sender, EventArgs e)
{
this.PopulateCombobox();
this.PopulateDataGridView();
}
private void PopulateCombobox()
{
string qry = "SELECT DISTINCT LastName FROM Employees";
string constr = @"Data Source=DESKTOP-Q2B3UUH\SQLEXPRESS;Initial Catalog=PeopleManager;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
using (SqlDataAdapter sda = new SqlDataAdapter(qry, con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow row = dt.NewRow();
row[0] = "";
dt.Rows.InsertAt(row, 0);
cbLastName.DataSource = dt;
cbLastName.DisplayMember = "LastName";
cbLastName.ValueMember = "LastName";
}
}
private void PopulateDataGridView()
{
string query = "SELECT EmpID, FirstName, LastName, Role, Grade, Dept, Shift FROM Employees";
query += " WHERE LastName = @LastName";
query += " OR ISNULL(@LastName, '') = ''";
string constr = @"Data Source=DESKTOP-Q2B3UUH\SQLEXPRESS;Initial Catalog=PeopleManager;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@LastName", cbLastName.SelectedValue);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
dgEmpList.DataSource = dt;
}
}
}
private void cbLastName_SelectionChangeCommitted(object sender, EventArgs e)
{
this.PopulateDataGridView();
}
}
答案 0 :(得分:0)
我会将("@LastName", cbLastName.SelectedValue)
更改为("@LastName", string.IsNullOrWhiteSpace(cbLastName.SelectedValue as string) ? DBNull.Value : ((string)cbLastName.SelectedValue).Trim())
然后
query += " WHERE LastName = @LastName";
query += " OR ISNULL(@LastName, '') = ''";
收件人
query += " WHERE (@LastName IS NULL OR LastName = @LastName)";
如果您的查询需要更多过滤器,只需添加更多这样的过滤器
query += " AND (@FooBar IS NULL OR FooBar = @FooBar)";
您还可以通过仅在脚本中包含所需的过滤器来创建动态脚本。第一个过滤器需要使用WHERE
和其他AND
答案 1 :(得分:0)
感谢万通快速回复! 讨厌这么说,但是除非我没有正确地应用它,否则我似乎并没有为我工作。 请看所附照片: enter image description here