Search code examples
c#datatable

How to DefultView Rowfilter add new


private void categoryCheckedListBox_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (e.State==CheckState.Checked)
            {
                string categoryName = categoryCheckedListBox.Items[e.Index].Value.ToString();
                (productListGV.DataSource as DataTable).DefaultView.RowFilter = string.Format("Kata2 LIKE '%{0}%' AND Kata1 LIKE '%{1}%'", categoryName,Cins);

            }
            else
            {
                (productListGV.DataSource as DataTable).DefaultView.RowFilter = null;
            }

        }

Hello Category always sounds different and dynamic. What I want is to add it to the filter for each selected checkbox value. CategoryName can have different value.

I did DefaultView.RowFilter+=.... but is error.


Solution

  • Iterate over categoryCheckedListBox.Items, compose your string.Format String based on the iterations and then pass to the string.Formats Object an array with the checked corresponding strings.

    Example:

    using System;
    using System.Linq;
    // Lacking actual data, I made an assumption that Kata concatenated with the key will correspond to the actual column
    (productListGV.DataSource as DataTable).DefaultView.RowFilter = string.Join(" AND ", new[] { "a", "b", "c" }.Select((val, key) => $"Kata{key} LIKE '%{val}%'" ));
    

    Or:

    using System;
    string[] a = new[] { "a", "b", "c" };
    string s = String.Empty;
    for (int i = 0; i < a.Length; i++) s+= $"Kata{i} LIKE '%{a[i]}%'";
    (productListGV.DataSource as DataTable).DefaultView.RowFilter = string.Format(s, a);
    

    I believe you get the picture.