datagridview绑定源过滤器

时间:2013-06-25 23:33:21

标签: c# datagridview filter bindingsource

我试图从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; }
}

2 个答案:

答案 0 :(得分:4)

到目前为止,这对我有用

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

}

答案 1 :(得分:0)

MSDN Documentation说:

  

仅实现IBindingListView接口的基础列表   支持过滤。

替换此

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

用这个

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