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.
- Start a new Windows application called MoreColors.
- Add a button named btnAdd.
- Add a ColorDialog control (appears in the panel under the form.)
- Create global variables for an integer ColorCount and an array called Colors with no dimension:
'Illustrate ReDim
Public Class Form1
'Programmer: Janet Joy
Dim ColorCount As Integer = 0
Dim MyColors() As Color
Private Sub DisplayColors()
'Draw a cirlce in each color in array
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(sender As Object, e As EventArgs) Handles BtnAdd.Click
'Let user select a color and add to array
Me.ColorDialog1.ShowDialog()
ColorCount = ColorCount + 1
ReDim Preserve MyColors(ColorCount)
MyColors(ColorCount) = Me.ColorDialog1.Color
DisplayColors()
End Sub
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.