簡體   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