簡體   English   中英

設置數據源時,從列表框中刪除列表中的元素

[英]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;
}

所有數據源都必須實現IListIListSource (例如, DataTable實現IListSource並且其GetList方法返回其DefaultView ),因此無論實際類型如何,您都可以始終以該類型訪問數據源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM