Search code examples
c#advanceddatagrid

Filter DataGridView via C# textbox with each word as a filter


Please I wanted to filter the grid view based on each word of the text box. where the filter has to search the data-grid each time I add a word consecutively. But in the code below it ends returning the search only depending on the last word. Please note that I am using a data grid view.

Any Advise

private void textBox1_TextChanged(object sender, EventArgs e) {

        int count = textBox1.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count();
        label68.Text = count.ToString();
        string[] nameParts = textBox1.Text.Split(' ');
        int cnlp = 1;

        while (cnlp <= count)
        {
            string loopcount = nameParts[(cnlp - 1)];
            lbtest5.Text = loopcount.ToString();
            var bd = (BindingSource)dgvShopDrawings.DataSource;
            var dt = (DataTable)bd.DataSource;
            dt.DefaultView.RowFilter = string.Format("DrawingID like '%{0}%' or title like '%{0}%'  or  level like '%{0}%'", lbtest5.Text.Replace("'", "''"));
            dgvShopDrawings.Refresh();
            ShopDrawingRecordCount = dt.Rows.Count;
            SdDgvStatusCount.Text = String.Format("Records In {0} / {1} ", dgvShopDrawings.Rows.Count, ShopDrawingRecordCount);
            cnlp = cnlp + 1;
        }

    }

Solution

  • You are replacing your RowFilter each iteration, so of cource it shows only the last one.

    Try something like this instead:

            int count = textBox1.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count();
            label68.Text = count.ToString();
            string[] nameParts = textBox1.Text.Split(' ');
            int cnlp = 1;
    
            string rowfilter = "";
            while (cnlp <= count)
            {
                string loopcount = nameParts[(cnlp - 1)];
                lbtest5.Text = loopcount.ToString();
                if (rowfilter.Length > 0) rowfilter += " AND ";
                rowfilter += tring.Format("(DrawingID like '%{0}%' or title like '%{0}%' or level like '%{0}%')", lbtest5.Text.Replace("'", "''"));
                cnlp = cnlp + 1;
            }
    
            var bd = (BindingSource)dgvShopDrawings.DataSource;
            var dt = (DataTable)bd.DataSource;
            dt.DefaultView.RowFilter = rowfilter;
            dgvShopDrawings.Refresh();
            ShopDrawingRecordCount = dt.Rows.Count;
            SdDgvStatusCount.Text = String.Format("Records In {0} / {1} ", dgvShopDrawings.Rows.Count, ShopDrawingRecordCount);