c# – datagridview绑定源过滤器
作者:互联网
我试图从BindingSource过滤数据 – 但它不起作用.
我究竟做错了什么?
我把我的代码简化为一个简约的例子.
问题是,如果我在TextBox中输入内容 – 没有任何反应.
public partial class Form1 : Form
{
BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
List<myObj> myObjList= new List<myObj>();
myObjList.Add(new myObj("LastNameA", "Peter"));
myObjList.Add(new myObj("LastNameA", "Klaus"));
myObjList.Add(new myObj("LastNameB", "Peter"));
foreach (myObj obj in myObjList)
{
bs.Add(obj);
}
dataGridView1.DataSource = bs;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
bs.Filter = string.Format("Name LIKE '%{0}%'", textBox1.Text);
dataGridView1.Refresh();
}
}
public class myObj
{
public myObj(string LastName, String Name)
{
this.LastName = LastName;
this.Name = Name;
}
public string LastName { get; set; }
public string Name { get; set; }
}
解决方法:
到目前为止,这对我有用
public partial class Form1 : Form
{
BindingSource bs = new BindingSource();
BindingList<myObj> myObjList = new BindingList<myObj>();
public Form1()
{
InitializeComponent();
myObjList.Add(new myObj("LastNameA", "Peter"));
myObjList.Add(new myObj("LastNameA", "Klaus"));
myObjList.Add(new myObj("LastNameB", "Peter"));
bs.DataSource = myObjList;
dataGridView1.DataSource = myObjList;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
BindingList<myObj> filtered = new BindingList<myObj>(myObjList.Where(obj => obj.Name.Contains(textBox1.Text)).ToList());
dataGridView1.DataSource = filtered;
dataGridView1.Update();
}
}
public class myObj
{
public myObj(string LastName, String Name)
{
this.LastName = LastName;
this.Name = Name;
}
public string LastName { get; set; }
public string Name { get; set; }
}
}
标签:c,filter,datagridview,bindingsource 来源: https://codeday.me/bug/20190625/1283654.html