设置数据源时从列表框中删除列表中的元素

Deleting a Element in a List from a Listbox when the Datasource is Set

我有一个存储球杆的 class (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 添加或删除项目。您必须通过数据源添加或删除。如果您可以直接访问 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;
}

所有数据源必须实现 IListIListSource(例如 DataTable 实现 IListSource 及其 GetList 方法 returns 它的 DefaultView) 因此您始终可以访问该类型的数据源,而不管其实际类型如何。