过滤DataGridView而不更改数据源 - null引用错误

时间:2014-03-25 10:20:31

标签: c# datagridview filtering

我想对已经加载到DataGridView中的数据实现一个简单的快速搜索/ aka过滤,而不会改变数据源。

这是我简单的用户界面:

enter image description here

这就是我尝试过滤数据的方式(基于回答here):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        List<Line> myLines = new List<Line>()
        {
            new Line() { Sku = "VCF001", Qty = 1 },
            new Line() { Sku = "VCF002", Qty = 1 },
            new Line() { Sku = "VCF003", Qty = 1 },
        };
        dataGridView1.DataSource = myLines;
    }

    private void searchBox_TextChanged(object sender, EventArgs e)
    {
        (dataGridView1.DataSource as DataTable).DefaultView.RowFilter 
            = string.Format("Sku LIKE '%{0}%'", searchBox.Text);
    }
}

public class Line
{
    public string Sku { get; set; }
    public int Qty { get; set; }
}

当我开始输入“VC”时,我收到此错误:

  

System.NullReferenceException未处理Message = Object引用   没有设置为对象的实例。

enter image description here

快速搜索/过滤应该如何工作:

  • 如果我输入“VC”,则应显示所有3行
  • 如果我输入“VCF001”,它应该只显示具有该sku的行

知道我在这里做错了吗?

2 个答案:

答案 0 :(得分:0)

类似的东西:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<Line> myLines {get;set;}

    private void Form1_Load(object sender, EventArgs e)
    {
        myLines = new List<Line>()
        {
            new Line() { Sku = "VCF001", Qty = 1 },
            new Line() { Sku = "VCF002", Qty = 1 },
            new Line() { Sku = "VCF003", Qty = 1 },
        };
        dataGridView1.DataSource = myLines;
    }

    private void searchBox_TextChanged(object sender, EventArgs e)
    {
        dataGridView1.DataSource = myLines.Where(l => l.Sku.ToLower().Contains(searchBox.Text.ToLower())).ToList();

    }
}

public class Line
{
    public string Sku { get; set; }
    public int Qty { get; set; }
}

答案 1 :(得分:0)

尝试使用以下内容:

dv.RowFilter = "Sku Like '%" + searchBox.Text + "%'