2017-04-17 48 views
1

我有一個名爲dgvAllBikes的gridView控件。在表單加載我加載dgvAllBikes。現在我想篩選這個基於三個選項和搜索按鈕的gridView,它是dgvAllBikes。如何基於多個選項過濾DataGridView?

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; 
    } 

我已經宣佈一流水平

string CS; 
    protected DataTable dtAllBike; 
    public SaleBike() 
    { 
     InitializeComponent(); 
     CS = ConfigurationManager.ConnectionStrings["BikeDB"].ConnectionString; 
    } 

數據表下面是圖片 enter image description here

這裏是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過濾,但我無法綁定另外兩個選項。您的幫助將非常感激。

回答

4

使用ORAND運營商創建一個過濾器上的多個值的作品。

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; 
} 
+0

非常棒..非常喜歡..非常感謝您的兄弟 –

+1

很高興能幫到你! =) –

相關問題