[英]Filter Datagridview rows using TextBox
I have a binded datagridView and i want to filter it using a TextBox value. 我有一个绑定的datagridView,我想使用TextBox值过滤它。
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 但是这个代码不会过滤datagridView,即使我使用了相同的代码
in another datagridView and it works perfectly. 在另一个datagridView中,它完美地运行。 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: 我删除了try catch,我收到此错误消息:
unable to cast object of type 'system.windows.forms.bindingsource' to type 'system.data.datatable'
无法将'system.windows.forms.bindingsource'类型的对象强制转换为'system.data.datatable'
How can i fix it?? 我该如何解决?
The DataSource is a type of BindingSource not DataTable, so try this code: DataSource是一种BindingSource而不是DataTable,所以请尝试以下代码:
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 . 您只需要使用Combobox来更改列号...只需使用您的想象力。
Thank you . 谢谢 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.