How to Determine Which Option Button is Selected in VB

Last reviewed: June 21, 1995
Article ID: Q88910
The information in this article applies to:
  • Standard and Professional Editions of Microsoft Visual Basic for Windows, versions 2.0 and 3.0
  • Microsoft Visual Basic programming system for Windows, version 1.0

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.

  • Place a command button (Command1) and option button (Option1) on Form1.

  • With Option1 selected, from the Edit menu, choose Copy.

  • From the Edit menu, choose Paste. A dialog box asks you if you want to create a control array. Choose Yes.

  • Change the Caption property of the two option buttons to "option 1" and "option 2".

  • Enter the following code into the general Declarations section of Form1:

    Dim option_index As Integer

  • Enter the following code into the Option1 control array Click event procedure:

       Sub Option1_Click (Index As Integer)
          option_index = Index
       End Sub
    
    

  • Enter the following code into the Command1 Click event procedure:

       Sub Command1_Click ()
          MsgBox Option1(option_index).Caption
       End Sub
    
    

  • Press F5 to run the program. When you click Command1, a dialog box displays the caption of the selected option button.


  • Additional reference words: 1.00 2.00 3.00
    KBCategory: kbprg kbcode
    KBSubcategory: PrgCtrlsStd


    THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

    Last reviewed: June 21, 1995
    © 1998 Microsoft Corporation. All rights reserved. Terms of Use.