Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you refresh a combo box item in-place?

The ComboBox Items collection is an ObjectCollection, so of course you can store anything you want in there, but that means you don't get a Text property like you would with, say, a ListViewItem. The ComboBox displays the items by calling ToString() on each item, or using reflection if the DisplayMember property is set.

My ComboBox is in DropDownList mode. I have a situation where I want to refresh the item text of a single item in the list when it gets selected by the user. The problem is that the ComboBox doesn't re-query for the text at any time besides when it loads up, and I can't figure out how else to do what I want besides removing and re-adding the selected item like so:


PlantComboBoxItem selectedItem = cboPlants.SelectedItem as PlantComboBoxItem;

// ...

cboPlants.BeginUpdate();

int selectedIndex = cboPlants.SelectedIndex;
cboPlants.Items.RemoveAt(selectedIndex);
cboPlants.Items.Insert(selectedIndex, selectedItem);
cboPlants.SelectedIndex = selectedIndex;

cboPlants.EndUpdate();

This code works fine, except for the fact that my SelectedIndex event ends up getting fired twice (once on the original user event, and then again when I re-set the property in this code). In this case, it's not a big deal that the event is fired twice, but it's inefficient, and I hate that. I could rig up a flag so it exits the event the second time, but that's hacking.

Is there a better way to get this to work?

like image 217
Jon Seigel Avatar asked Sep 17 '09 17:09

Jon Seigel


People also ask

Which method is used to add the items in a ComboBox?

To add a set of items to the combo box it is best to use the AddRange method. If you choose to use the Add method to add a number of items to the combo box, use the BeginUpdate method to suspend repainting during your add and the EndUpdate method to resume repainting.

How do I make my ComboBox not editable?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: stateComboBox.

How do I make my ComboBox read only?

Just change the DropDownStyle to DropDownList . Or if you want it completely read only you can set Enabled = false , or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.


1 Answers

A dirty hack:

typeof(ComboBox).InvokeMember("RefreshItems", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, cboPlants, new object[] { });
like image 103
TOS Avatar answered Sep 22 '22 23:09

TOS