简体   繁体   中英

C# ListBox : Items collection cannot be modified when the DataSource property is set

I have created following function to call for delete the selected record from database and also from the listbox, which will get call on button Delete Record .

Function :

void DeleteListBox2()
{
    string connstring = String.Format("Server=localhost;Port=***;" +
   "User Id=****;Password=****;Database=****;");

    NpgsqlConnection conn = new NpgsqlConnection(connstring);
    conn.Open();

    for (int i = 0; i < listBox2.SelectedItems.Count; i++)
    {

        var itemname = listBox2.SelectedValue;
        NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM Table WHERE Value = '" + itemname + "'", conn);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Selected record deleted from database");
        listBox2.Items.Remove(listBox2.SelectedItems[i]); //ERROR LINE
        listBox2.Update();

    }
    conn.Close();
}

ERROR :

Items collection cannot be modified when the DataSource property is set.

It would help to provide additional details such as what frameworks you are using, WPF, Winforms etc.

Your ListBox should have its data source bound to a List object. Then instead of deleting directly from the list view component, you should delete from the List that the view is bound to and then notify the UI that there are changes and it will update accordingly.

Here is a good read on binding your list view to a list object: Binding Listbox to List

A quick google search will return results on how to update UI once changes have been made, here is one for winforms: How to refresh DataSource of a ListBox in C# WinForms

I would suggest after you delete the items in the database to read it again. Since you probably want to have a recent mapping from database to the display.

After that just reattach the DataSource property to the new record collection.

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