动态添加SqlParameter参数,动态添加where条件
List<SqlParameter> ilist = new List<SqlParameter>();
ilist.Add(new SqlParameter("@Param1", "1"));
ilist.Add(new SqlParameter("@Param2", "2"));
ilist.Add(new SqlParameter("@Param3", "3"));
ilist.Add(new SqlParameter("@Param4", "4"));
ilist.Add(new SqlParameter("@ParamLike","%5%"));//Like的写法
SqlParameter[] param = ilist.ToArray();
List<string> listWhere = new List<string>();
List<SqlParameter> listParameters = new List<SqlParameter>();
if (cbName.Checked)
{
listWhere.Add("Name like @name");
listParameters.Add(new SqlParameter("name","%"+txtQueryName.Text+"%"));
}
if (cbMobile.Checked)
{
listWhere.Add("MobilePhone like @mobile");
listParameters.Add(new SqlParameter("mobile", "%" + txtQueryMobile.Text + "%"));
}
string sql = "select * from T_Customers\n";
if (listWhere.Count > 0)
{
string sqlWhere = string.Join(" and ", listWhere.ToArray());
sql =sql+" where "+sqlWhere;
}
dataGridView1.DataSource = SqlHelper.ExecuteDataTable(sql, listParameters.ToArray());