问题
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
回答1:
I suggest going for a DataGridView
.
I will be able to hold 1000s of records.
You have a choice of either
- sticking to its straight grid-like layout or
- chose a hybrid layout
By that I mean a solutuion that shows all but the current record as one row in the grid; the current one can be enlarged and overlaid by one instance of your UserControl
that gets loaded from the underlying row's data whenever the selected row changes.
See this post for an example of this technique; there I show how to replace the current row with a larger area, much in the way an accordion control would work..
The rows in the DGV are in fact just a Bitmap
and therefore cheap to scroll; the normal way to use a DGV is to rely on its ability the overlay one cell with an edit control of the right type.
The 'accordion trick' extends this to an arbitrary UserControl
overlaying a whole row.
Note that the other rows will take a lot less space, which I see as a bonus..
来源:https://stackoverflow.com/questions/35379100/winforms-scrollable-flowlayoutpanel-with-thousands-of-user-controls-how-to-pr