starsign

Hi,

I have written a custom combobox that inherits from combobox into which I load 5 objects. This is part of the custom combobox code (within the constructor).

When I put this combobox on to a form and see it in action the combobox contains 10 items - the original 5 plus the same 5 repeated.

I have looked at the form's designer code and can see that within InitialiseComponent there is code to add the 5 objects into the combobox, which the custom combobox already has loaded, hence why I get 10. If i remove this code the combo works fine, but isn't there a way to set up the custom combo so that it doesn't cause a form to load the objects back into itself

Any help would really be appreciated.



Re: Windows Forms General adding objects to custom combobox

nobugz

Your problem is that the control's constructor runs at design time as well as runtime. When you first drop the control on a form, the constructor runs and adds the 5 items. The designer dutifully records those items in the Designer.cs file. Then when you run, you again create 5 items, then get the 5 items added that were recorded at design time.

You don't want to add the items at design time. Problem is, you cannot yet find out whether you are in design mode or not in the constructor. You'll have to do it later. A decent, but not perfect, place to do this is in the OnHandleCreated() method. Check this thread for an example.





Re: Windows Forms General adding objects to custom combobox

starsign

thank you, really appreciate your help.



Re: Windows Forms General adding objects to custom combobox

starsign

Hi, having implemented this I just wanted to come back with the solution that eventually worked for me. I tried overriding the onhandlecreated method and this cured the problem of having the items loaded into the control twice - the desiner now does not include the code to load the items. However, an error occured when the application was running with the combo was dropped down and I tried to scroll down to the end of the list of items. The error was flagging that the selectedindex was not valid - i.e. greater than the amount of items in the control, from the scrollbar in dropdown portion it looked like it was scaled to be twice as many items (if that makes sense) but the item count was correct.

I tried a few different things and eventually found that if I put the loading of the combobox items in the oncreatecontrol method then everything worked fine.

I don't know why I was getting the error when the code was in the oncreatehandle method - if anyone has any info then please let me know, likewise if there are any issues with using oncreatecontrol.





Re: Windows Forms General adding objects to custom combobox

nobugz

Thanks for the feedback. I like OnCreateControl() better, OnHandleCreated() may run more than once when the application code changes the combobox style. That's why I put the test in the code to check that the items weren't already added.