【问题标题】:Converting DataSource to DataTable returns null while filtering DataGridView过滤 DataGridView 时将 DataSource 转换为 DataTable 返回 null
【发布时间】:2018-03-01 00:33:56
【问题描述】:

我完全不熟悉 Windows 窗体,尤其是 DataGridView 控件。 问题是当我想按特定列过滤 DataGridView 时。

在表单加载事件中,我将数据绑定到DataGridViewDataSource,如下所示:

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}%'";
}

但问题是dt 变为nulldataGridView1.DataSource 具有值和记录数。

【问题讨论】:

  • 你使用过dataGridView1.DataBind(); ?
  • 您正在将人员列表绑定到网格视图。列表不能转换为数据表,这是简单的逻辑。这就是为什么你得到空值。
  • 需要将GridView的DataSource转成BindingList,并使用linq进行过滤。
  • 我试过你的解决方案,它工作正常。您可能想提交答案(详细)非常感谢 @ChetanRanpariya

标签: c# winforms search datagridview filtering


【解决方案1】:

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}%'";
}

【讨论】:

  • 我认为您仍然可能需要分配 DataTable 以避免在方法返回后它被垃圾收集。
  • 抱歉,分配给什么?
  • 将本地 DataTable dt 作为某个属性(DataSource?)分配给 DataGridView
  • 不确定这是否是需要的。让 OP 决定
【解决方案2】:
y = x as DataTable;

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

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

如果你想使用它的功能,你必须自己创建一个 DataTable 对象。

【讨论】:

    猜你喜欢
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多