1. 程式人生 > >多ComboBox實現復雜查詢

多ComboBox實現復雜查詢

index 專業 () axu 復雜 表名 分享圖片 != 選中

技術分享圖片

 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 前面有個空格

多ComboBox實現復雜查詢