-1

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.

MAK
  • 6,824
  • 25
  • 74
  • 131
  • 4
    You should remove the items from the underlying object associated to the DataSource. – Steve Feb 16 '17 at 09:08
  • or, you can change the way listbox items are populated. Iterate thru your dataset and insert intems into listbox. That way you'll be able to remove specific item from listbox. – Nino Feb 16 '17 at 09:11
  • By the way, be careful of the way you are connecting to the database! If you have an exception, the connection won't be closed. Use a using block. Also, use command parameters, or your app will be vulnerable to SQL injection. – Zesty Feb 16 '17 at 09:12
  • 1
    *"Items collection cannot be modified when the DataSource property is set."* It doesn't get any more specific than that. It precisely tells you what's wrong - you've set the DataSource so you can't modify the items directly. – Manfred Radlwimmer Feb 16 '17 at 09:26

2 Answers2

2

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

Community
  • 1
  • 1
Mark Atkinson
  • 458
  • 8
  • 14
1

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.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76