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??
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();
}
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With