5

我正在尝试从 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; }
}
4

2 回答 2

2

到目前为止,这对我有用

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

}

于 2013-06-26T09:58:51.957 回答
-1

MSDN文档

只有实现 IBindingListView 接口的基础列表才支持筛选。

替换这个

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

有了这个

 BindingList<myObj> myObjList= new BindingList<myObj>();
于 2013-06-25T23:41:23.290 回答