C#如何使用DataSource隐藏一行
-
12-09-2019 - |
题
我有许多用户的数据源(BindingList),但是我不想在DataGridView中显示一些用户。是否可以隐藏它们。我找不到有效的事件。
Rowsadd有时会隐藏werng行。
解决方案
看来我必须实现自己的过滤器。我为BindingList Wich构建一个适配器可以显示任何BindingList的过滤版本。您只需继承它即可。这是我的例子。我想仅向用户显示用户。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;
好的,过滤器属性毫无用处。但是适配器类非常实验。但是,对于简单的添加和删除数据杂志,它似乎运行良好。
这是适配器的代码:
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上找到一些示例。 这个 看起来很有趣...
不隶属于 StackOverflow