5

I have a binded datagridView and i want to filter it using a TextBox value.

I used this code:

private void ChercheStextBox_TextChanged(object sender, EventArgs e)
    {
        try
        {
            ((DataTable)dataGridView3.DataSource).DefaultView.RowFilter = string.Format("LibService like '%{0}%'", ChercheStextBox.Text.Trim().Replace("'", "''"));
        }
        catch
        {

        }

    }

But this code doesn't filter the datagridView even i have used the same code

in another datagridView and it works perfectly. I don't know where is the

error in my code?

Thanks in advance.

EDIT:

i removed try catch and i got this error message:

unable to cast object of type 'system.windows.forms.bindingsource' to type 'system.data.datatable'

How can i fix it??

10
  • Are you sure the column name (LibService) is correct?
    – sloth
    Feb 10, 2015 at 13:36
  • Yes i'm sure it is correct Feb 10, 2015 at 13:38
  • Have you bound the eventhandler to the right event? Put a breakpoint into that method and check the RowFilter property before leaving the method
    – sloth
    Feb 10, 2015 at 13:50
  • Have you looked at the resulting filterstring? Care to post it?
    – TaW
    Feb 10, 2015 at 13:54
  • 3
    Get rid of that empty try-catch. It's not helping you.
    – LarsTech
    Feb 10, 2015 at 15:43

2 Answers 2

10

The DataSource is a type of BindingSource not DataTable, so try this code:

private void ChercheStextBox_TextChanged(object sender, EventArgs e)
    {
        var bd = (BindingSource)dataGridView3.DataSource;
        var dt = (DataTable)bd.DataSource;
        dt.DefaultView.RowFilter = string.Format("LibService like '%{0}%'", ChercheStextBox.Text.Trim().Replace("'", "''"));    
        dataGridView3.Refresh();


    }
2
  • Is this possible to count and get HeaderText and filter? actually, I don't want to specify any particular header value. Dec 3, 2016 at 7:26
  • The first line didn't work, as the datagrid view casts to a DataTable. So it was sufficient to cast the datagridview datasource to the datatable and use it. ``var dt = (DataTable)dataGridView3.DataSource;
    – sm2mafaz
    Apr 14, 2023 at 12:04
1

I think you need to use this Method :

 public void ChercheStextBox_TextChanged(object sender, EventArgs e)
    {
          //NASSIM LOUCHANI
          BindingSource bs = new BindingSource();
          bs.DataSource = dataGridView3.DataSource;
          bs.Filter = string.Format("CONVERT(" + dataGridView3.Columns[1].DataPropertyName + ", System.String) like '%" + ChercheStextBox.Text.Replace("'", "''") + "%'");
          dataGridView3.DataSource = bs;

    }

All you need is change the Columns Number using a Combobox for Example ... just use your imagination .

Thank you .

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.