[英]Deleting a Element in a List from a Listbox when the Datasource is Set
我有一个存储俱乐部的课程(Global.Clubes)。 每个俱乐部都有一个名称,总裁和成员。 我将成员存储在BingingList中。 我使用DataSource在列表框中显示了BindingList中存储的所有人员。 我现在正在尝试删除列表框中的项目,由于它与数据源绑定,因此应该更新成员的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
或从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
),因此无论实际类型如何,您都可以始终以该类型访问数据源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.