Drawing in Visual Basic

You can only select one radio button from a group. If you want to have more than one group you need to put each group in a separate container. The form is one container. Other containers include groupBoxes and panels. In the program shown below, we have used groupBoxes to create two groups of buttons. The groupBox has text, the panel does not. Notice that we can select both a color and a shape.

Build the form as shown. It is important to put the groupBox on the form first, then draw the radioButtons inside the groupBox. Drag the groupBox. If the radioButton moves with it, it is inside the groupBox. If not, delete the radio button and try again. After creating the first groupBox you can copy and paste to create the second group.

This form has the following controls:

  • Group Box grpShape contains radCircle and radSquare.
  • GroupBox grpColor contains radRed and radBlue.

Write code as shown below:

'Programmer: Janet Joy
'Illustrate group boxes
Public Class Form1
    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        Dim MyPen As New Pen(Color.Goldenrod, 3)
        If Me.RadBlue.Checked Then
            MyPen.Color = Color.Blue
        ElseIf Me.RadRed.Checked Then
            MyPen.Color = Color.Red
        End If
        If Me.RadCircle.Checked Then
            Me.CreateGraphics.DrawEllipse(MyPen, e.X, e.Y, 20, 20)
        Else
            Me.CreateGraphics.DrawRectangle(MyPen, e.X, e.Y, 20, 20)
        End If
    End Sub
End Class

NEXT: Drawing lines