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

}

上一篇:一个合格的嵌入式软件开发工程师要掌握哪些知识?


下一篇:Linux c++ vim环境搭建系列(0)——简介