多ComboBox实现复杂查询

 1 关键是,你是要实现什么功能:是四个条件都有内容时查询,还是哪个内容有查哪个?
 2 如果四个组合框都有内容,相对简单些:
 3 string s = "select * from 表名 where 身份='" + comboBox1.SelectedItem.ToString() + "' and 部门='" + comboBox2.SelectedItem.ToString() + "' and 专业='" + comboBox3.SelectedItem.ToString() + "' and 班级='" + comboBox4.SelectedItem.ToString() + "'";
 4 如果想得到的效果是:选中哪个组合框,按哪个内容查询,比如说,选中身份和部门,按这两个查询,未选择的也不会出错,这样就相对麻烦些,需要拼凑SQL语句:
 5 string tou = "select * from 表名 where 1=1";
 6             string wei = "";
 7             if (comboBox1.SelectedIndex != -1)
 8             {
 9                 wei += " and 身份='" + comboBox1.SelectedItem.ToString() + "'";
10             }
11             if (comboBox2.SelectedIndex != -1)
12             {
13                 wei += " and 部门='" + comboBox2.SelectedItem.ToString() + "'";
14             }
15             if (comboBox3.SelectedIndex != -1)
16             {
17                 wei += " and 专业='" + comboBox3.SelectedItem.ToString() + "'";
18             }
19             if (comboBox4.SelectedIndex != -1)
20             {
21                 wei += " and 班级='" + comboBox4.SelectedItem.ToString() + "'";
22             }
23             string chaxun = tou + wei;
24 最后的chaxun即为拼凑好的查询语句,注意后一种方法中,每个and 前面有个空格
原文地址:https://www.cnblogs.com/xiaowie/p/9059264.html