【发布时间】:2020-06-05 03:57:32
【问题描述】:
我在 Windows 窗体中有一个 dataGrid (dataGridView1)。 dataGridView1 在表单加载时从业务对象中填充。这按预期工作:
bs.DataSource = oBadger_History.GetChild();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bs;
我有一个 dateTimePicker (dateTimePicker1),在 dateTimePicker1_ValueChanged 上,我想过滤 dataGridView1 结果以仅显示在 dateTimePicker1 中选择的日期 (v_issue_date) 的结果。我已经尝试了以下(使用过滤器)。 .但似乎无法让它工作。也许第二双眼睛会有所帮助?
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "M/d/yyyy";
cs.DataSource = bs.Filter = string.Format("v_issue_date LIKE '{0}%' ", dateTimePicker1.Text);
dataGridView1.DataSource = cs;
dataGridView1.Update();
dataGridView1.Refresh();
请记住,我对 c# 比较陌生。我进行了搜索(这里和谷歌),虽然有一些很好的信息,但它与我想要实现的目标没有直接关系。
在上述场景中,DataGridView1 会刷新 - 但刷新不会显示应用的过滤器。
只是为了排除日期类型不匹配的可能性——我做了一个非常简单的过滤器——但 DataGridView1 确实刷新了但没有显示过滤后的数据。
BindingSource cs = new BindingSource();
cs.DataSource = dataGridView1.DataSource;
cs.Filter = "[v_firstname] = 'Jose'";
dataGridView1.DataSource = cs;
dataGridView1.Update();
dataGridView1.Refresh();
这些失败的尝试模拟了我在网上看到的大多数示例。 .所以我不确定为什么没有应用过滤器。
编辑 - *********
为了简单起见,我在下面发布了负载和事件:
private void ChildReport_Load(object sender, EventArgs e)
{
//BindingSource bs = new BindingSource();
bs.DataSource = oBadger_History.GetChild();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bs;
}
private void dateTimePicker1_ValueChanged_1(object sender, EventArgs e)
{
bs.Filter = string.Format("v_issue_date = '{0:yyyy/MM/dd}'", dateTimePicker1.Value);
dataGridView1.DataSource = bs.Filter;
dataGridView1.Update();
dataGridView1.Refresh();
}
在上面的示例中,表格会刷新,但它总是返回为空。未找到匹配项。不确定是什么问题。 v_issue_date 是一个日期类型字段。我已经在调试中放置了停止,我可以验证 dateTimePicker.Value 是否在表中。不知道为什么我不能拔出火柴。
编辑 2 **********
这是我用来填充 DataGridView1 的业务对象。
public daBindingList<Badger_History> GetChild()
{
BadgerContext cn = (BadgerContext)this.context;
var entityKist = cn.Badger_History.Where(b => b.v_child == "Child").ToList();
this.EntityList = new daBindingList<Badger_History>(entityKist);
return this.EntityList;
}
【问题讨论】:
-
不清楚为什么代码要引入第二个
BindingSource...BindingSource cs = new BindingSource(); cs.DataSource = dataGridView1.DataSource;?是否有某些原因您不使用原始BindingSource作为过滤器?此外,我相信您不能将“LIKE”或“通配符”(%) 与“DATES”一起使用。 LIKE 和通配符仅适用于字符串,不适用于数字/日期值。您将需要使用“>、 -
另外,在过滤器字符串上,代码使用
DataTimePickersText属性,它是一个“字符串”……值应该是DateTime对象,因此您需要使用 DTP 的Value财产。我通过删除不必要的第二个绑定源获得了成功,并在原始绑定源上使用了以下过滤器...bs.Filter = string.Format("Date = '{0:yyyy/MM/dd}'", dateTimePicker1.Value); -
@JohnG - 我没有特别的理由为过滤器创建第二个 BindingSource - 除了我已经绝望并尝试了任何东西。我在尝试实施您的建议时仍然遇到问题。我将清理我的代码并稍后重新发布编辑。
-
将行
dataGridView1.DataSource = bs.Filter;更改为dataGridView1.DataSource = bs;... 也不需要刷新和更新。 -
@JohnG - 我设置 Datasource = bs.Filter 的原因是因为当我设置 Datasource = bs; datagridview 数据永远不会改变。就好像过滤器不存在一样。我得到的是原始的 FULL bs 数据源,而不是过滤后的版本。
标签: c# datagridview