ReDim: Change the Size of the Array

The ReDim statement let’s you change the size of an array at run time. The keyword Preserve prevents the current values from being erased when you change the size of the array. We are going to create an array of colors adding each one to the array when the user selects the color from the color dialog. We will display all of the colors in the array by drawing a circle in each color.

  1. Start a new Windows application called MoreColors.
  2. Add a button named btnAdd.
  3. Add a ColorDialog ColorDialogcontrol (appears in the panel under the form.)
  4. Create global variables for an integer ColorCount and an array called Colors with no dimension:
Public Class Form1
    Dim ColorCount As Integer = 0
    Dim MyColors() As Color
    Private Sub DisplayColors()
        Dim MyBrush As New SolidBrush(Color.Red) 'any color
        Dim X, Y, N As Integer
        X = 0
        Y = Me.BtnAdd.Location.Y + Me.BtnAdd.Height 'below the button
        For N = 0 To ColorCount
            MyBrush.Color = MyColors(N)
            Me.CreateGraphics.FillEllipse(MyBrush, X, Y, 15, 15)
            X = X + 15
            If X > Me.Width - 15 Then 'move to next row
                X = 0 'back to beginning of row
                Y = Y + 15
            End If
        Next N
    End Sub 'DisplayColors
    Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e _
      As System.EventArgs) Handles BtnAdd.Click
        ColorCount = ColorCount + 1
        ReDim Preserve MyColors(ColorCount)
        MyColors(ColorCount) = Me.ColorDialog1.Color
    End Sub 'BtnAdd_Click
End Class
Run the program. Each time you select a color, the list of colors is displayed as a series of dots.

Experiment: Use For Each instead of For in the loop.

Next Page: No Duplicates