【问题标题】:Binding dataGridView to bindinglist and filter rows by textbox将dataGridView绑定到绑定列表并通过文本框过滤行
【发布时间】:2014-05-21 08:29:38
【问题描述】:

我正在开发一个 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_;
    }
}

【问题讨论】:

  • 您的 DataSource 是 BindingList,而不是 DataTable。
  • 你说得对,谢谢。但是主要问题仍然存在,如何使这个 TextBox 过滤 dataGridView?
  • 您必须创建一个新的 BindingList 进行过滤。使用 LINQ 很容易做到。见Filtering a Binding List

标签: c# winforms data-binding datagridview filter


【解决方案1】:

根据 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);
    }
}

【讨论】:

  • 这样,当您从 blist 添加或删除项目时,文本框不会收到通知。您必须另外调用 OnPropertyChanged。
猜你喜欢
  • 2016-02-07
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多