简体   繁体   English

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

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

I have got a class (Global.Clubes) that stores clubes. 我有一个存储俱乐部的课程(Global.Clubes)。 Each clube has a name, president and members. 每个俱乐部都有一个名称,总裁和成员。 I stored the members in BingingList. 我将成员存储在BingingList中。 I used DataSource to show in a listbox all the people stored in the BindingList. 我使用DataSource在列表框中显示了BindingList中存储的所有人员。 I'm now trying to remove the item in the listbox and since its binded with datasource it should update the BindingList of members... How can I do this though? 我现在正在尝试删除列表框中的项目,由于它与数据源绑定,因此应该更新成员的BindingList ...但是我该怎么做? I've searched and I haven't found a solution for this problem. 我已经搜索过,但没有找到解决该问题的方法。

    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;
            }
        }
    }

Items cannot be added to or removed from a ListBox directly when it is bound. 绑定项目时,不能直接将项目添加到ListBox或从ListBox删除项目。 You must add or remove via the data source. 您必须通过数据源添加或删除。 If you have direct access to the BindingList then you can use that. 如果您可以直接访问BindingList则可以使用它。 If you don't have direct access to the data source, here's a method that can be used for any data source: 如果您无权直接访问数据源,则可以使用以下方法来处理任何数据源:

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;
}

All data sources must implement either IList or IListSource (eg DataTable implements IListSource and its GetList method returns its DefaultView ) so you can always access the data source as that type, regardless of its actual type. 所有数据源都必须实现IListIListSource (例如, DataTable实现IListSource并且其GetList方法返回其DefaultView ),因此无论实际类型如何,您都可以始终以该类型访问数据源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM