简体   繁体   中英

Binding dataGridView to bindinglist and filter rows by textbox

I'm working on a Winforms application and I have a BindingList of objects that I already bind to a dataGridView.
I also have a "Filter" textbox that I want to filter the rows out of the datagridview rows if they do not match the textbox text. I somehow want to connect the textbox to a column to hide the relevant rows. How can I do this?

So here is the code:

public partial class Form1 : Form
{

    BindingList<SWItem> blist = new BindingList<SWItem>();

    public Form1()
    {
        InitializeComponent();

        dataGridView1.AutoGenerateColumns = false;
        this.ServerName.DataPropertyName = "ServerName";
        this.SoftwareName.DataPropertyName = "SoftwareName";

        dataGridView1.DataSource = blist;

        blist.Add(new SWItem("item1", "bla"));
        blist.Add(new SWItem("item2", "bla"));
        blist.Add(new SWItem("item3", "bla"));
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            string Filter = string.Format("ServerName like '%{0}%'", textBox1.Text.Trim().Replace("'", "''"));
            (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = Filter;
        }
        catch (Exception ex)
        {
            new ToolTip().SetToolTip(textBox1, ex.Message);
        }
    }
}

public class SWItem
{
    public string ServerName { get; set; }
    public string SoftwareName { get; set; }

    public SWItem(string ServerName_, string SoftwareName_)
    {
        ServerName = ServerName_;
        SoftwareName = SoftwareName_;
    }
}

According to LarsTech's comment I have updated the textBox1_TextChanged function and it works properly now. Thank you LarsTech!

private void textBox1_TextChanged(object sender, EventArgs e)
{
    try
    {
        string Filter = textBox1.Text.Trim().Replace("'", "''");
        dataGridView1.DataSource = new BindingList<SWItem>(blist.Where(m => m.ServerName.Contains(Filter)).ToList<SWItem>());
    }
    catch (Exception ex)
    {
        new ToolTip().SetToolTip(textBox1, ex.Message);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM