This code seems to be very simple, but it's taking a long time to run. I've made a sample project with only the basic code included and it's still very slow.
I have a form with a button and a panel. At runtime the panel is dynamically filled with approx 1700 custom User controls. The custom user control contains one panel and one property. Clicking the button on the form causes each user control to swap its color. This action should happen all at once, but it's so slow that I can watch each user control switch color, row, by row, one at a time
Can I suspend screen updating until after the whole for each loop runs, rather than updating each panel one by one?
User Control code...
Public Class ucBox
Private _TurnedOn As Boolean
Public Property TurnedOn() As Boolean
Get
Return _TurnedOn
End Get
Set(ByVal value As Boolean)
_TurnedOn = value
If TurnedOn Then
PnlBox.BackColor = Color.Red
Else
PnlBox.BackColor = Color.LightGray
End If
End Set
End Property
Private Sub PnlBox_Click(sender As Object, e As EventArgs) Handles PnlBox.Click
If TurnedOn Then
TurnedOn = False
Else
TurnedOn = True
End If
End Sub
End Class
Form Code...
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim Rw As Int16 = 0, Col As Int16 = 0, x As Int16
Dim Box As ucBox
With btnTest
.Text = "Test Me"
End With
While Rw < PnlMain.Height - 10
While Col < PnlMain.Width - 10
Box = New ucBox
x = x + 1
With Box
.Top = Rw
.Left = Col
.TurnedOn = False
.Name = "Box_" & x
Col += .Width + 4
End With
PnlMain.Controls.Add(Box)
Box = Nothing
End While
Col = 0
Rw += 24
If x > 2000 Then Exit While
End While
Debug.Print("There are " & x & " boxes.")
End Sub
Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
Dim StartTime As Date = Now
For Each b As ucBox In PnlMain.Controls
If b.TurnedOn Then
b.TurnedOn = False
Else
b.TurnedOn = True
End If
Next
Debug.Print("Test took " & Now.Subtract(StartTime).TotalMilliseconds)
End Sub
End Class
I appreciate any ideas.