1 private void button1_Click(object sender, EventArgs e) 2 { 3 StringBuilder sbSql = new StringBuilder("select * from student "); 4 List<string> wheres = new List<string>(); 5 List<SqlParameter> parameters = new List<SqlParameter>(); 6 foreach (Control ct in panel1.Controls) //遍歷容器中的集合 7 { 8 //這裏只介紹一種思惟方式,具體邏輯還需改造方法 9 if (ct is TextBox) //文本框 10 { 11 wheres.Add(" "+ct.Name+" like @"+ct.Name+" "); //ct.Name:獲取控件的Name屬性,必須有命名規則,和數據庫字段相同 12 parameters.Add(new SqlParameter("@"+ct.Name+"","'%"+ct.Text.Trim()+"%'")); 13 continue; 14 } 15 if (ct is CheckBox) 16 { 17 //複選框 18 } 19 if (ct is DateTimePicker) 20 { 21 //日期控件 22 } 23 if (ct is ComboBox) 24 { 25 //下拉框 26 } 27 } 28 //開始多條件搜索拼接 29 if (wheres.Count>0) //有值 30 { 31 sbSql.Append(" where "); 32 sbSql.Append(string.Join(" and ",wheres.ToArray())); //調用字符串鏈接 string.Join 33 } 34 MessageBox.Show(sbSql.ToString()); //多條件拼接SQL成功! 35 }