Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Datagridview rows using TextBox

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??

like image 754
user4428204 Avatar asked Feb 10 '15 13:02

user4428204


2 Answers

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();


    }
like image 56
user4340666 Avatar answered Oct 25 '22 03:10

user4340666


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 .

like image 40
nassimlouchani Avatar answered Oct 25 '22 03:10

nassimlouchani