I am relatively new to windows form programming. I am developing a windows form application which requires user to scroll through the form (I have used a FlowLayoutPanel with AutoScroll=True inside the form). The Panel's source contains an user control which is looped through depending on the number of records.
For instance, if 10 records are present in DB, then 10 user controls are created and added into the Panel when the Form loads, and user will be able to scroll through the 10 items.(Please see the sample image which depicts this scenario) Sample Screen Image
Issue:
The problem occurs when there are more number of records (say 1000), since the usercontrol objects are not disposed and the Handle limit is exceeded, the application crashes (with a message: Error creating window handle). I am aware that this is a memory leak or issue with a bad design.
But I am unable to find a reliable solution here, i have thought about the below options (to overcome the issue) but not sure how to proceed on these:
- Load only the UserControls visible on the users screen and dispose other userControls on the fly (as user scrolls or when up/down button is pressed)
- Would it be possible to render the usercontrols as image in the panel, and on hovering or clicking of any part, the user control can be re-initialized and triggered to load (This way, the actual user control object would not be in memory)
Could you please suggest a suitable solution / the right way of handling the UserControl objects in the context of this requirement