C#中多條件查詢
C#中多條件查詢
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 多條件查詢
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(cboSearchClass.SelectedItem);
string name = txtSearchName.Text;
string geder = cboSearchGender.SelectedItem!=null? cboSearchGender.SelectedItem.ToString():null;
bool hasdate = chkIsByDate.Checked;
MessageBox.Show(GetSearchStudents(id,name,geder));
}
public string GetSearchStudents(int cid, string name, string sex)
{
string sql = "select * from v_Students where PIsDel=0 and pType=1";
List<Person> students = new List<Person>();
List<SqlParameter> list = new List<SqlParameter>();//存引數
//站著埋
if (cid != -1)
{
sql += " and pcid=@cid";
list.Add(new SqlParameter("@cid", cid));
}
if (!string.IsNullOrEmpty(name))
{
sql += " and PCName like @name";
list.Add(new SqlParameter("@name", "%" + name + "%"));
}
if (!string.IsNullOrEmpty(sex) && sex != "不限")
{
sql += " and pSex=@sex";
list.Add(new SqlParameter("@sex", sex));
}
return sql;
}
}
}