【问题标题】:datagridview binding source filterdatagridview 绑定源过滤器
【发布时间】:2013-06-26 17:58:51
【问题描述】:

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

【问题讨论】:

    标签: c# datagridview filter bindingsource


    【解决方案1】:

    到目前为止,这对我有用

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

    }

    【讨论】:

      【解决方案2】:

      MSDN Documentation 说:

      仅实现 IBindingListView 接口的底层列表 支持过滤。

      替换这个

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

      有了这个

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

      【讨论】:

      • 我已经阅读了 MSDN 文档,现在已经应用了 BindingList。但是如果我在 TextBox 中输入字母 - 什么都不会发生
      • BindingList&lt;T&gt; 没有实现 IBindingListView
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2012-05-15
      • 1970-01-01
      相关资源
      最近更新 更多