2016-01-07 57 views
0

當用戶點擊我的一個datagridview的列並選擇過濾時,會彈出一個窗口,其中列表框將填充該列的值(不重複 - 表示如果有5個0它只顯示一次)。C#根據列表框的多個選項過濾datagridview

這是彈出窗口的初始化。

public partial class ComboBoxFilter : Form 
{ 

    DataGridView Dgv; 
    DataGridViewColumn Col; 
    DataView View; 
    string CName; 

    public ComboBoxFilter(DataGridView dgv, DataGridViewColumn col, DataView view, string colName) 
    { 
     InitializeComponent(); 
     Dgv = dgv; 
     Col = col; 
     View = view; 
     CName = colName; 
     listBox1.ValueMember = col.DataPropertyName; 
     listBox1.DisplayMember = col.DataPropertyName; 
     DataTable dt = view.ToTable(true, new string[] { col.DataPropertyName }); 
     dt.DefaultView.Sort = col.DataPropertyName; 
     listBox1.ClearSelected(); 
     listBox1.DataSource = dt; 
    } 

當用戶從列表框中一個值,按下OK按鈕:

private void buttonOK_Click(object sender, EventArgs e) 
    { 
     BindingSource bs = (BindingSource)Dgv.DataSource; 
     bs.Filter = string.Format("{0} = '{1}'", CName, listBox1.SelectedValue.ToString()); 
     Dgv.DataSource = bs; 
     this.Close(); 
    } 

其中CNAME是列的待過濾的名字。

This works great。

但是,現在我想允許我的列表框中的multiselect屬性,以便如果用戶選擇多個值,我可以過濾。我怎樣才能做到這一點?是否有必要像我在一些例子中看到的那樣使用「OR」?

+0

移動控件到窗體構造讓我毛骨悚然。 – Ralf

回答

1

按照DataView.RowFilterDataColumn.Expression文檔,可以使用ORIN運營商建立過濾標準,符合IMO後來是更適合這個場景。

因此,代碼可能是這樣的

private void buttonOK_Click(object sender, EventArgs e) 
{ 
    var selection = string.Join(",", listBox1.SelectedItems.Cast<object>() 
     .Select(item => "'" + listBox1.GetItemText(item) + "'").ToArray()); 
    var filter = listBox1.SelectedItems.Count == 0 ? string.Empty : 
     listBox1.SelectedItems.Count == 1 ? string.Format("{0} = {1}", CName, selection) : 
     string.Format("{0} IN ({1})", CName, selection); 

    var bs = (BindingSource)Dgv.DataSource; 
    bs.Filter = filter; 
    this.Close(); 
} 
相關問題