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:
Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles BtnAdd.Click
Me.ColorDialog1.ShowDialog()
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
DisplayColors()
End If
End Sub 'BtnAdd_Click
Function ColorInArray(ByVal Clr As Color) As Boolean
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
Experiment: 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.