Thursday, 2 August 2007

MFC List Box

List Box Exercise

A list box presents a list of items to the user to choose from with each item on its own line. The user makes a selection by clicking in the list. Once clicked, an item becomes highlighted indicating that it is the current choice. A list box can be configured to allow single or multiple selections.

One of the main reasons for using a list box is to display a list of items on specific lines to the user. Sometimes the list would be very large. If the list is longer than the available space on a form, the control would provide a scroll bar that allows the user to navigate up and down and then access all items of the list. The application developer decides how many items to display on the list.

To create a list box, you can use the List Box button from the Controls toolbox.

Testing the Program as you Progress

  • To test the result, anytime, press Ctrl + F5.

Creating the Application

  1. Start Microsoft Visual C++

  2. On the main menu, click File -> New.

  3. Decide to create a Dialog Based application called ListOfCountries with a title as
    List of Countries

  4. While designing the dialog box, place a List Box control on it. Change the identifier of the   list box to IDC_LIST_COUNTRIES

  5. Place an Edit Box on the dialog. Call it IDC_LISTDBLCLK

  6. Right-click the List Box and click ClassWizard...

  7. Click the Member Variables property sheet.

  8. Double-click IDC_LISTCOUNTRIES to Add a Variable

  9. Set the Member Variable Name to m_ListCountries

  10. In the Category combo box, select Control

    Add Member Variable

  11. Click OK

  12. Also Add a Variable for the IDC_LISTDBLCLK   control and named m_ListResult based on CString

Adding Items to a List Box

  • In the OnInitDialog() function of the dialog box, initialize the list box as follows:
    // TODO: Add extra initialization here
    m_ListCountries.AddString("Costa Rica");

Select an Item Using its Position

  • To set the 4th item in the list box as selected, under the last AddString() function in the OnInitDialog, add the following line.

Transfer an Item to an Edit Box After Double-Clicking in the List

  1. Press Ctrl + W to access the ClassWizard.

  2. Click the Message Maps property sheet. In the Class Name combo box, make sure CListExoDlg is selected. In the Object IDs, click IDC_LISTCOUNTRIES

  3. In the Messages list, double-click LBN_DBLCLK. Change the name of the function to OnDblclkList and click OK.

  4. Click Edit Code and implement the function as follows

No comments:

Post a Comment