Removing a collection of controls
controls, vb.net
Solution
Hiding the Panel first seems to make the controls disappear quicker than just clearing the Panel. See this code:
Option Strict On
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Panel1.Visible = False
If Not Panel1.Controls.OfType(Of Button).Any() Then
For x As Integer = 1 To 10
For y As Integer = 1 To 10
Dim btn As New Button()
btn.Size = New Size(45, 45)
btn.Location = New Point((x - 1) * 45, (y - 1) * 45)
btn.Text = (x * y).ToString()
Panel1.Controls.Add(btn)
btn.Visible = True
Next
Next
End If
Panel1.Visible = True
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Panel1.Visible = False
Panel1.Controls.Clear()
Panel1.Visible = True
End Sub
End Class
This code has 2 buttons, and a Panel. Button1 generates 100 buttons, places them on a Panel. Button2 hides the panel before removing them. Perhaps you can experiment with this idea.
Problem
I have a form (Form1) and it has 30 controls. When I hit a button, I want to remove those 30 buttons and put other controls on the form. Now, my problem is that this is to slow. I have this list with controls I want to delete and I run through them with a For Each. ``` Private Sub ClearControls() 'removing the controls from Me.Controls For Each Control As Control In ListToDelete Me.Controls.Remove(Control) Next ListToDelete = New List(Of Control) End Sub ``` Now, if you watch the form, you see the controls getting deleted 1 by 1. This action takes about 0.4 seconds (timed with the build-in stopwatch) and that's too long. Are there any solutions to delete the controls in a faster way or is it only possible to delete the controls 1 by 1? Maybe an important fact is that everything is connected with a database. The controls are created by a class I defined myself (TableDrawer) and it creates a rectangle or circle (depends on info from the database). I add the selfmade controls to the form and when I want to delete them, it takes 0.4 seconds to get other controls on the form - also with information out of my database. Hopefully this clears some things up and I hope you can help me out... It really has to go a bit faster (I hope to get 0.1s or lower)