C# 使用C进行多组合框搜索

C# 使用C进行多组合框搜索,c#,winforms,drop-down-menu,C#,Winforms,Drop Down Menu,我想从使用3个不同组合框的数据库中搜索数据 我想单击“搜索”按钮,单击后,我希望数据显示在所有“选择”组合框中 数据应该完全按照我选择的3组合框显示。那我该怎么做呢?谢谢你的帮助 现在,我使用if-else,但我想像上面所说的那样更改它们 private void btnsubmit_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=(Loca

我想从使用3个不同组合框的数据库中搜索数据

我想单击“搜索”按钮,单击后,我希望数据显示在所有“选择”组合框中

数据应该完全按照我选择的3组合框显示。那我该怎么做呢?谢谢你的帮助

现在,我使用if-else,但我想像上面所说的那样更改它们

  private void btnsubmit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
        DataTable ds = new DataTable();

        if (comboBox1.Text.Length > 0)
        {
            SqlDataAdapter sda = new SqlDataAdapter("SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student where Program LIKE '" + comboBox1.Text + "%' ", con);
            sda.Fill(ds);

        }
        else if (comboBox2.Text.Length > 0)
        {

            SqlDataAdapter sda = new SqlDataAdapter("SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student where State LIKE '" + comboBox2.Text + "%' ", con);
            sda.Fill(ds);
        }
        else if (comboBox3.Text.Length > 0)
        {
            SqlDataAdapter sda = new SqlDataAdapter("SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student where Kohort LIKE '" + comboBox3.Text + "%' ", con);
            sda.Fill(ds);
        }

作为一种通用方法,您需要动态组合您选择的条件

String query = "SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student";
List<String> conditions = new List<String>();
if (comboBox1.Text.Length > 0)
{
    conditions.Add("Program LIKE '" + comboBox1.Text + "%' ");
}
if (comboBox2.Text.Length > 0)
{
    conditions.Add("State LIKE '" + comboBox2.Text + "%' ");
}
if (comboBox3.Text.Length > 0)
{
    conditions.Add("Kohort LIKE '" + comboBox3.Text + "%' ");
}

if (conditions.Count > 0)
{
    query = query + " WHERE " + String.Join(" AND ", conditions.ToArray())
}
SqlDataAdapter sda = new SqlDataAdapter(query, con);
sda.Fill(ds);

你想要什么查询?我只是编辑我的代码和上面的问题@克里希纳