1、界面
二、代码示例(提供一种思维,根据实际情况还需改造)
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 }
原文地址:https://www.cnblogs.com/chenyanbin/p/10850964.html
时间: 2024-10-24 16:24:12