user5557067
user5557067

Reputation: 13

How to create thousand buttons quickly?

I have a program that can create 4000 new buttons but it took me 30 second to complete it. Is there anyway to make it faster?

For x = 1 To 4000

    Dim btnNew As New Button()

    btnNew.Width = 14
    btnNew.Height = 11

    btnNew.Location = New Point(a, b)
    Me.Controls.Add(btnNew)
    btn(k) = btnNew

Next

Upvotes: 1

Views: 102

Answers (1)

Carlos Aguilar Mares
Carlos Aguilar Mares

Reputation: 13601

There are three things that you really need to do:

  1. Call SuspendLayout/ResumeLayout (to save all the multiple-layouts)
  2. You could call AddRange instead.
  3. If the container supports BeginUpdate/EndUpdate then use those two (to save re-painting).

So try:

Me.SuspendLayout()
Try
    For x As Integer = 1 To 4000

        Dim btnNew As New Button()

        btnNew.Width = 14
        btnNew.Height = 11

        btnNew.Location = New Point(a, b)
        Me.Controls.Add(btnNew)
        btn(k) = btnNew

    Next
Catch ex As Exception
    Throw
Finally
   Me.ResumeLayout()
End Try

Upvotes: 4

Related Questions