我有一个数据绑定到 BindingList 的 DataGridView
private void InitGrid()
{
Ctx.MyEntitySet.Load();
dataGridView1.DataSource = Ctx.MyEntitySet.Local.ToBindingList();
dataGridView1.Columns["Id"].Visible = false;
dataGridView1.Columns["UnwantedCol1"].Visible = false;
dataGridView1.Columns["UnwantedCol2"].Visible = false;
dataGridView1.Columns["UnwantedCol3"].Visible = false;
}
和一个过滤文本框,一个 TextChanged 事件像这样处理
private void textBoxFilter_TextChanged(object sender, EventArgs e)
{
try
{
string filter = textBoxFilter.Text.Trim();
((DataView)dataGridView1.DataSource).RowFilter = filter;
textBoxFilter.BackColor = SystemColors.AppWorkspace;
}
catch (Exception)
{
textBoxFilter.BackColor = Color.Red;
ToolTip tip = new ToolTip();
tip.SetToolTip(textBoxFilter, ex.Message);
}
}
我运行代码,数据正确显示,但是当我尝试ColumnName like '%sometext%'
在我的过滤器文本框中键入类似的内容时,我收到一个异常,说我无法投射'System.Data.Entity.Internal.ObservableBackedBindingList`1[MyEntity] ' 到 'System.Data.DataView'。
谁能给我指点?
谢谢,F。
解决:
添加了通用扩展方法
public static class LocalExtensions
{
public static IEnumerable<T> Filter<T>(this IEnumerable<T> list, Func<T, bool> filterParam)
{
return list.Where(filterParam);
}
}
并像这样修改了 TextChanged 事件处理程序:
private void textBoxFilter_TextChanged(object sender, EventArgs e)
{
try
{
string filter = textBoxFilter.Text.Trim();
dataGridView1.DataSource =
Ctx.MyEntitySet.Local
.Filter(x =>
x.EntityPropertyToSearchIn1.ToUpper().Contains(filter.ToUpper()) ||
x.EntityPropertyToSearchIn2.ToUpper().Contains(filter.ToUpper())
).ToList();
textBoxFilter.BackColor = SystemColors.AppWorkspace;
}
catch (Exception)
{
textBoxFilter.BackColor = Color.Red;
ToolTip tip = new ToolTip();
tip.SetToolTip(textBoxFilter, ex.Message);
}
}