[英]c# How to hide a row in a DataGridView with DataSource
我有一个包含许多用户的数据源(BindingList),但是有些用户不想在我的DataGridView中显示。 是否可以隐藏它们。 我找不到有效的事件。
排行有时会隐藏破旧的行。
看来我必须实现自己的过滤器。 我为BindingList构建了一个适配器,它可以显示任何BindingList的过滤版本。 您只需要继承它即可。 这是我的例子。 我只想显示具有user.CanEdit = true的用户
public class AhpUserFilter : FilterBindingListAdapter<AhpUser>
{
public AhpUserFilter(AhpUserCollection users)
: base(users.GetList() as IBindingList)
{
}
protected override bool ISVisible(AhpUser user)
{
return user.CanEdit;
}
}
这是将新列表绑定到DatagridView的方法:
AhpUserFilter userSource = new AhpUserFilter(users);
userSource.Filter = "yes!";
dataGridViewUser.DataSource = userSource;
好的,Filter属性是没有用的。 但是Adapter类还处于实验阶段。 但是对于使用DataGrid进行简单的添加和删除来说,它似乎运行良好。
这是适配器的代码:
public class FilterBindingListAdapter<T> : BindingList<T>, IBindingListView
{
protected string filter = String.Empty;
protected IBindingList bindingList;
private bool filtering = false;
public FilterBindingListAdapter(IBindingList bindingList)
{
this.bindingList = bindingList;
DoFilter();
}
protected override void OnListChanged(ListChangedEventArgs e)
{
if (!filtering)
{
switch (e.ListChangedType)
{
case ListChangedType.ItemAdded:
bindingList.Insert(e.NewIndex, this[e.NewIndex]);
break;
}
}
base.OnListChanged(e);
}
protected override void RemoveItem(int index)
{
if (!filtering)
{
bindingList.RemoveAt(index);
}
base.RemoveItem(index);
}
protected virtual void DoFilter()
{
filtering = true;
this.Clear();
foreach (T e in bindingList)
{
if (filter.Length == 0 || this.ISVisible(e))
{
this.Add((T)e);
}
}
filtering = false;
}
protected virtual bool ISVisible(T element)
{
return true;
}
#region IBindingListView Members
public void ApplySort(ListSortDescriptionCollection sorts)
{
throw new NotImplementedException();
}
public string Filter
{
get
{
return filter;
}
set
{
filter = value;
DoFilter();
}
}
public void RemoveFilter()
{
Filter = String.Empty;
}
public ListSortDescriptionCollection SortDescriptions
{
get { throw new NotImplementedException(); }
}
public bool SupportsAdvancedSorting
{
get { return false; }
}
public bool SupportsFiltering
{
get { return true; }
}
#endregion
}
您可以使用BindingSource.Filter
属性过滤行。 但是, BindingList<T>
的内置实现不支持过滤,因此您需要自己实现。 您可以在Google上找到一些示例。 这个看起来很有趣...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.