【发布时间】:2018-03-01 00:33:56
【问题描述】:
我完全不熟悉 Windows 窗体,尤其是 DataGridView 控件。
问题是当我想按特定列过滤 DataGridView 时。
在表单加载事件中,我将数据绑定到DataGridView 的DataSource,如下所示:
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 变为null 而dataGridView1.DataSource 具有值和记录数。
【问题讨论】:
-
你使用过dataGridView1.DataBind(); ?
-
您正在将人员列表绑定到网格视图。列表不能转换为数据表,这是简单的逻辑。这就是为什么你得到空值。
-
需要将GridView的DataSource转成BindingList
,并使用linq进行过滤。 -
我试过你的解决方案,它工作正常。您可能想提交答案(详细)。 非常感谢 @ChetanRanpariya
标签: c# winforms search datagridview filtering