Winforms: Scrollable FlowLayoutPanel with thousands of user controls - How to prevent memory leaks and dispose objects the right way? [closed]

梦想的初衷 提交于 2020-12-31 01:43:16

问题


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:

  1. 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)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!