Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datagridview binding source filter

I am trying to filter Data out of a BindingSource - but it doesnt work. What am i doing wrong? I have reduced my Code to a minimalistic example.

The Problem is, if i type something in the 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; }
}
like image 665
Blindsurfer Avatar asked Nov 13 '22 02:11

Blindsurfer


1 Answers

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

}

like image 150
Blindsurfer Avatar answered Nov 15 '22 11:11

Blindsurfer