我有一个存储俱乐部的类(Global.Clubes(。每个俱乐部都有一个名字,总裁和成员。我将成员存储在Binglist。我使用DataSource在列表框中显示所有存储在BindingList中的人。我现在试图在列表框中删除该项目,并且由于它与数据源相关,因此应该更新会员的绑定清单...但是我该怎么做?我已经搜索过,但我还没有找到解决这个问题的解决方案。
private void btn_remove_Click(object sender, EventArgs e)
{
foreach (var item in Global.clubes)
{
if (cbo_clubes.Text == item.nome)
{
lst_members.Items.Remove(lst_members.SelectedItem);
lst_members.DataSource = item.pessoas;
}
}
}
当绑定时,无法直接从ListBox
添加或删除项目。您必须通过数据源添加或删除。如果您可以直接访问BindingList
,则可以使用它。如果您无法直接访问数据源,则以下是可用于任何数据源的方法:
private bool RemoveBoundItem(ListBox control, object item)
{
// Try to get the data source as an IList.
var dataSource = control.DataSource as IList;
if (dataSource == null)
{
// Try to get the data source as an IListSource.
var listSource = control.DataSource as IListSource;
if (listSource == null)
{
// The control is not bound.
return false;
}
dataSource = listSource.GetList();
}
try
{
dataSource.Remove(item);
}
catch (NotSupportedException)
{
// The data source does not allow item removal.
return false;
}
// The item was removed.
return true;
}
所有数据源都必须实现IList
或IListSource
(例如DataTable
实现IListSource
及其GetList
方法返回其DefaultView
(,因此您始终可以访问该类型的数据源,无论其实际类型如何。