Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Radio Buttons in MFC (Visual Studio 2008 / C++)

0.00/5 (No votes)
25 Aug 2010 1  
A quick and dirty description of how to use radio buttons in MFC

This is a quick and dirty description of how to use radio buttons in MFC, written because I could not find this information in a single place on the web.

In the dialog editor:

  • Create a new group with the group box control and set a meaningful caption.
  • Add radio button controls inside the group.
  • The radio buttons must have ascending tab order.
  • The first radio button (in tab order) must have the property "Group" set to True.
  • All other radio buttons must have the property "Group" set to False.

It should look similar to this:

In the header file defining the dialog class:

  • Add a member variable of type int that will store which radio button is selected (none: -1, first: 0, second: 1, and so on).
    Example:
    C++
    int m_nLEDType;

In the CPP file implementing the dialog class:

  • In the constructor, initialize the member variable (with 0)
    Example:
    C++
    CDialogConfig::CDialogConfig(CMainFrame* pMainFrame) : 
    	CDialog(CDialogConfig::IDD, pMainFrame), m_nLEDType(0)
  • In DoDataExchange, add a call to DDX_Radio similar to the following (where IDC_RADIO_LEDTYPE1 is the ID of the first radio button):
    C++
    DDX_Radio(pDX, IDC_RADIO_LEDTYPE1, m_nLEDType);

When you want to read which radio button is selected:

  • Call UpdateData with a parameter of true (indicates reading):
    C++
    UpdateData (TRUE);
  • After UpdateData has been called, the member variable (m_nLEDType in this example) has the current state of the buttons.

When you want to select one of the buttons programmatically:

  • Set the member variable to the correct value (none selected: -1, first button selected: 0, second button selected: 1, and so on)
  • Call UpdateData with a parameter of false (indicates writing):
    C++
    UpdateData (FALSE);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here