Deleting items from a list box after you set DataSource


I have a small requirement and that is as follows:

I am populating a ListBox using stored procedures and the ListBox is populated as follows:

lstItems.DisplayMember = "emp_name"
lstItems.ValueMember = "login_id"
lstItems.DataSource = accessFunction.getEmployees

The ListBox gets populated correctly. After it is populated, i have a CommandButton and on the click event of the button, i want to remove selected items from the ListBox. So in the click event of the CommandButton, i have written the following code:


After selecting an item from the ListBox and when i click the CommandButton, i get an error as "Items collection cannot be modified when the DataSource property is set".

Can anyone, please help me as to how i can delete items from the ListBox.

Regards, George

Two easy things to try:

  1. Rather than databind, you could fill your list with a loop. Remember to add proper NULL handling (I didn't):

    For each dr as DataRow in myDataTable.Rows newItem = new ListItems(dr("login_id"), dr("emp_name")) lstItems.Add newItem Next

  2. Save the datatable from your accessFunction in a variable. Delete the row from the datatable and rebind.