繁体   English   中英

将dataGridView绑定到bindinglist并按文本框过滤行

[英]Binding dataGridView to bindinglist and filter rows by textbox

我正在使用Winforms应用程序,我有一个已绑定到dataGridView的对象的BindingList。
我还有一个“过滤器”文本框,如果它们与文本框文本不匹配,我想从datagridview行中过滤掉这些行。 我想以某种方式将文本框连接到列以隐藏相关的行。 我怎样才能做到这一点?

所以这是代码:

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

根据LarsTech的评论,我更新了textBox1_TextChanged函数,现在它可以正常工作。 谢谢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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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