How to Determine Which Option Button is Selected in VB (88910)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 2.0
  • Microsoft Visual Basic Standard Edition for Windows 3.0
  • Microsoft Visual Basic Professional Edition for Windows 2.0
  • Microsoft Visual Basic Professional Edition for Windows 3.0
  • Microsoft Visual Basic Standard Edition for Windows 1.0

This article was previously published under Q88910

SUMMARY

This article describes a suggested method for determining which one of a group of option buttons is selected.

MORE INFORMATION

You can do the following to determine which option button is selected:

  1. Make the group of option buttons a control array.
  2. In the Click event handler for the control array, save the index of the selected option button into a global variable.
  3. When you want to know which option button is selected, check the global variable.
An alternative method to check which option button was selected is to examine the Value property of each option button in a sequence of If-Then statements, or in a Select Case statement.

Step-by-Step Example

  1. Start Visual Basic or from the File menu, choose New Project (ALT, F, N) if Visual Basic is already running. Form1 is created by default.
  2. Place a command button (Command1) and option button (Option1) on Form1.
  3. With Option1 selected, from the Edit menu, choose Copy.
  4. From the Edit menu, choose Paste. A dialog box asks you if you want to create a control array. Choose Yes.
  5. Change the Caption property of the two option buttons to "option 1" and "option 2".
  6. Enter the following code into the general Declarations section of Form1:
       Dim option_index As Integer
    						
  7. Enter the following code into the Option1 control array Click event procedure:
       Sub Option1_Click (Index As Integer)
          option_index = Index
       End Sub
    						
  8. Enter the following code into the Command1 Click event procedure:
       Sub Command1_Click ()
          MsgBox Option1(option_index).Caption
       End Sub
    						
  9. Press F5 to run the program. When you click Command1, a dialog box displays the caption of the selected option button.

Modification Type:MajorLast Reviewed:12/12/2003
Keywords:KB88910