Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from ComboBox (DropDownList) Winforms

I have a dropdownlist which has been populated

ddlNumbers.DisplayMember = "PhoneNumber";
ddlNumbers.DataSource = mobileList;
ddlNumbers.SelectedItem = null;

When a button is clicked I want to remove an item from it.

ddlMobileNumbers.Items.RemoveAt(i);

But get the exception. 'Items collection cannot be modified when the DataSource property is set...'

I have also tried re-assigning a collection to the DataSource

ddlNumbers.DataSource = myNewList

But does not work.

What am I doing wrong here?

like image 207
ojhawkins Avatar asked May 25 '26 21:05

ojhawkins


1 Answers

You can't remove an item from a list when its bound to a control, You can temporarily null the data source of the bound control and remove the item from list and then set the data source again.

Something like,

//Null the datasource
Combobox1.Datasource = null;

//Remove the item
ddlMobileNumbers.Items.RemoveAt(i);

//Set the source again
Combobox1.Datasource = ddlMobileNumbers;
like image 171
Kurubaran Avatar answered May 28 '26 12:05

Kurubaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!