Arrays in Visual Basic

The way the program is written we could add red several times. The modification below adds the selected color only if it is not in the array already. If the color is already in the array, a message box pops up to tell them that it is a duplicate.

We will start by writing a function to find the position of the color in the array. A function is the same as a sub (subroutine or procedure) except that it returns an answer. This function will return a Boolean because we only need to know if it is in the array or not. Notice that the value of a color is passed as an argument. The "As" clause after the parenthesis tells the type that will be returned. The last statement that the function executes must assign a value to the function.

The global declarations and DisplayColors were not changed and do not appear here:
'Illustrate ReDim
Public Class Form1
    'Programmer: Janet Joy
    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
        'Draw a circle in each color
        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
        Me.ColorDialog1.ShowDialog() 'user selects color
        If ColorInArray(Me.ColorDialog1.Color) Then 'if duplicate
            Me.Text = Me.ColorDialog1.Color.ToString & " is already in the list"
        Else 'add if not a duplicate
            Me.Text = Me.ColorDialog1.Color.ToString
            ColorCount += 1
            ReDim Preserve MyColors(ColorCount)
            MyColors(ColorCount) = Me.ColorDialog1.Color
        End If
    End Sub
    Function ColorInArray(ByVal Clr As Color) As Boolean
        'Returns true if the color is already in array
        Dim Found As Boolean = False
        Dim Num As Integer = 0
        While ColorCount > 0 And Num <= ColorCount And Found = False
            If MyColors(Num) = Clr Then Found = True
            Num += 1
        End While
        ColorInArray = Found
    End Function 'ColorInArray
End Class

: Call DisplayColors when the form is resized. This event occurs after the form is minimized so that the colors will display when the program is activated.

Experiment: Add a button that lets the user start a new list.

NEXT: Collections