在过滤DataGridView时,将DataSource转换为DataTable会返回null

时间:2017-09-20 05:10:09

标签: c# winforms search datagridview filtering

我对Windows Forms完全陌生,特别是DataGridView控件。 问题是我希望按特定列过滤DataGridView

在表单加载事件中,我将数据绑定到DataSource的{​​{1}},如下所示:

DataGridView

然后点击事件private void Main_Load(object sender, EventArgs e) { BindingSource bs = new BindingSource(); BindingList<Person> pList = new BindingList<Person> { new Person {Id = 5, FName = "James", LName = "Allan", Age = 23, Country = "United States"}, // And so on ... }; bs.DataSource = pList; dataGridView1.DataSource = bs.DataSource; }

button1

但问题是private void button1_Click(object sender, EventArgs e) { DataTable dt = dataGridView1.DataSource as DataTable; if (dt != null) dt.DefaultView.RowFilter = $"FName LIKE '%{textBox1.Text}%'"; } 变为dtnull有值和记录数。

2 个答案:

答案 0 :(得分:0)

BindingList无法转换为DataTable

How to make a DataTable from DataGridView without any Datasource?您可以查看此内容。

private void button1_Click(object sender, EventArgs e) {   
    DataTable dt = new DataTable();
    foreach(DataGridViewColumn col in dataGridView1.Columns)
    {
        dt.Columns.Add(col.HeaderText);    
    }

    foreach(DataGridViewRow row in dataGridView1.Rows)
    {
        DataRow newrow = dt.NewRow();
        foreach(DataGridViewCell cell in row.Cells)
        {
            newrow[cell.ColumnIndex] = cell.Value;
        }
        dt.Rows.Add(newrow);
    }
    dt.DefaultView.RowFilter = $"FName LIKE '%{textBox1.Text}%'";
}

答案 1 :(得分:0)

y = x as DataTable;

不是BindingList的转换,而是(通常)equal to

if(x is DataTable)
    y = (DataTable)x;
else
    y = null;

如果要使用其功能,则必须自己创建一个DataTable对象。