解决方法:
首先应该设置一个int变量,用来判断用户选中的条件是否超过两个,如果超过两个,我们就进行查询,这里我用的是
字符串的拼接。
int num=0;
string sqlStr="select <列名> from <表名> where "
if(建筑面积 != null)
{
sqlStr+="建筑面积=@建筑面积";
num++;
}
if(户型 != null)
{
sqlStr+="and 户型=@户型";
num++;
}
if(装修情况 != null)
{
sqlStr+="and 装修情况=@装修情况";
num++;
}
if(价格 != null)
{
sqlStr="and 价格=@价格";
num++;
}
if(房屋情况 != null)
{
sqlStr+="and 房屋情况=@房屋情况";
num++;
}
if(num<=2)
{
//提示用户应选择多项,用个Label,或是脚本都可以
return;
}
//连接数据库,使用时记得先导入
命名空间Using System.Data.SqlClient和using System.Data;
using(SqlConnection con=new SqlConnection("server=.;uid=sa;password=123456;database=数据库名"))
{
using(SqlCommand cmd=con.CreateCommand())
{
cmd.CommandText=sqlStr;
con.Open();
DataSet ds=new DataSet();
SqlDataAdapter sda=new SqlDataAdapter(cmd);
sda.Fill(ds);
dataGridView.DataSource=ds.Tables[0].DefaultView;//这个dataGridView是你的DataGridView控件的名字
dataGridView.DataBind();
}
}
这样访问后就能在DataGridView控件中显示筛选出的数据了,只需将上述代码修改下,放在一个按钮事件中就可以了。祝好远。