我有一个名为dgvAllBikes的gridView控件。在表单加载时,我加载dgvAllBikes。现在我想基于三个选项和一个搜索按钮过滤这个基于dgvAllBikes的gridView。
1)CC
2)模型
3)颜色
当我点击搜索按钮时,我想根据这三个选项过滤dgvAllBikes。
这是我的LoadGrid代码
private DataTable LoadGrid()
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spGetAllBikes", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader r = cmd.ExecuteReader();
dtAllBike = new DataTable();
dtAllBike.Load(r);
}
return dtAllBike;
}
我已在班级
中声明了DataTablestring CS;
protected DataTable dtAllBike;
public SaleBike()
{
InitializeComponent();
CS = ConfigurationManager.ConnectionStrings["BikeDB"].ConnectionString;
}
以下是btnSearch的代码。
private void btnSearch_Click(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
bs.DataSource = dgvAllBikeDetails.DataSource;
bs.Filter = dgvAllBikeDetails.Columns["CC"].HeaderText.ToString() + " LIKE '%" + tbCCSearch.Text + "%'";
dgvAllBikeDetails.DataSource = bs;
它基于CC过滤但我无法绑定其他两个选项。非常感谢您的帮助。
答案 0 :(得分:5)
使用OR
或AND
运算符创建适用于多个值的过滤器。
private void btnSearch_Click(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
bs.DataSource = dgvAllBikeDetails.DataSource;
string filter = "";
// Check if text fields are not null before adding to filter.
if (!string.IsNullOrEmpty(tbCCSearch.Text))
{
filter += dgvAllBikeDetails.Columns["CC"].HeaderText.ToString() + " LIKE '%" + tbCCSearch.Text + "%' ";
}
if (!string.IsNullOrEmpty(tbModelSearch.Text))
{
if (filter.length > 0) filter += "OR ";
filter += dgvAllBikeDetails.Columns["Model"].HeaderText.ToString() + " LIKE '%" + tbModelSearch.Text + "%' ";
}
if (!string.IsNullOrEmpty(tbCCSearch.Text))
{
if (filter.length > 0) filter += "OR ";
filter += dgvAllBikeDetails.Columns["Color"].HeaderText.ToString() + " LIKE '%" + tbColorSearch.Text + "%' ";
}
bs.Filter = filter;
dgvAllBikeDetails.DataSource = bs;
}