简体   繁体   中英

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

I have got a class (Global.Clubes) that stores clubes. Each clube has a name, president and members. I stored the members in BingingList. I used DataSource to show in a listbox all the people stored in the 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? 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. You must add or remove via the data source. If you have direct access to the BindingList then you can use that. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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