如图,下拉框都是相同的,有三个选项:单位工程,移交单位,移交人分别对应数据库中的Name,Yjdw,Yjr字段,该如何实现3个3个textbox中填了几个就实现现几个条件的查询(同时满足下拉框选择的)。单纯的if肯定是会非常麻烦的,求个简便点的方法,谢谢!
如图,下拉框都是相同的,有三个选项:单位工程,移交单位,移交人分别对应数据库中的Name,Yjdw,Yjr字段,该如何实现3个3个textbox中填了几个就实现现几个条件的查询(同时满足下拉框选择的)。单纯的if肯定是会非常麻烦的,求个简便点的方法,谢谢!
string strsql = "select * from tbName where 1=1";
if(txtBox1.Text!="") strsql+= " and Name='"+txtBox1.Text+"'";
if(txtBox2.Text!="") strsql+= " and Yhdw='"+txtBox2.Text+"'";
if(txtBox3.Text!="") strsql+= " and Yjr='"+txtBox3.Text+"'";
stringBuilder 拼接 条件 字符串
if (!String.IsNullOrEmpty(where))
{
sql += " where " + where;
}
if(txtBox1.Text!="") strsql+= " and Name='"+txtBox1.Text+"'";
if(txtBox2.Text!="") strsql+= " and Yhdw='"+txtBox2.Text+"'";
if(txtBox3.Text!="") strsql+= " and Yjr='"+txtBox3.Text+"'";
1=1 是一个永真的表达式,这么写是为了确保where已经在字符串内,不会重复添加。不然要进行3个条件的查询时,就会出现3个where了。
strsql += (txtBox1.Text==""?"": " and Name like '%"+txtBox1.Text+"%'");
strsql += (txtBox2.Text==""?"": " and Yhdw like '%"+txtBox2.Text+"%'");
strsql += (txtBox3.Text==""?"": " and Yjr like '%"+txtBox3.Text+"%'");
{
if (ddl_text == "单位工程")
{
return " and Project_Name like '%" + text + "%'";
}
if (ddl_text == "移交单位")
{
return " and Project_Yjdw like '%" + text + "%'";
}
if (ddl_text == "移交人")
{
return " and Project_Yjr like '%" + text + "%'";
}
return text;
}调用方法
string sql = "select Project_Name from UDP_Project where 1=1";
sql += SQLHelper.selected(ddl_ProName.Text, txt_Key.Text);
sql += SQLHelper.selected(ddl_ProName2.Text, txt_Key2.Text);
sql += SQLHelper.selected(ddl_ProName3.Text, txt_Key3.Text);