Datagridview binding source filter

I am trying to filter Data from a BindingSource, but it does not work. What am I doing wrong? I cut my code to a minimalistic example.

The problem is that if I type in a TextBox, nothing happens.

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; } } 
+4
source share
2 answers

It has worked for me so far

 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; } } 

}

+4
source

The MSDN documentation says:

Only basic lists that implement the IBindingListView interface filtering support.

Replace it

  List<myObj> myObjList= new List<myObj>(); 

with this

  BindingList<myObj> myObjList= new BindingList<myObj>(); 
0
source

Source: https://habr.com/ru/post/1488186/


All Articles