Home

Windows Controls: The List Box

    

Introduction to List Boxes

 

Description

A list box presents a list of items to choose from. Each item displays on a line:

Date and Time

The user makes a selection by clicking in the list. Once clicked, the item or line on which the mouse landed becomes highlighted, indicating that the item is the current choice. Once an item is selected, to make a different selection, the user would click another. The user can also press the up and down arrow keys to navigate through the list and make a selection.

As far as item selection is concerned, there are two types of list boxes: single selection and multiple selection.

One of the main reasons for using a list box is to display a list of items to the user. Sometimes the list would be very large. If the list is longer than the available space on the control, the operating system would provide a scroll bar that allows the user to navigate up and down to access all items of the list. Therefore, you will have the option of deciding how many items to display on the list.

Practical LearningPractical Learning: Introducing List Boxes

  1. Start Microsoft Visual Studio
  2. To start a new application, on the main menu, click File -> New Project...
  3. In the middle list, click MFC Application and change the Name to MeasuesOfCenter1
  4. In the first page of the wizard, click Next
  5. In the second page of the wizard, click Dialog Based and click Next
  6. Click Finish

Creating a List Box

To include a list box in your application, from the Toolbox, you can click the List Box button List Box and click on a parent window. After visually adding the control, if you intend to refer to it in your code, you should create a member variable for it.

The MFC list box is based on the CListBox class. Therefore, if you want to programmatically create a list box, declare a CListBox variable or pointer using its constructor. To initialize the control, call its Create() member function. Its syntax is:

virtual BOOL Create(DWORD dwStyle,
   		    const RECT& rect,
   		    CWnd* pParentWnd,
   		    UINT nID);

Here is an example:

BOOL CExerciseDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);			// Set big icon
    SetIcon(m_hIcon, FALSE);		// Set small icon

    // TODO: Add extra initialization here
    CListBox *m_SimpleList = new CListBox;

    m_SimpleList->Create(WS_CHILD | WS_VISIBLE,
			 CRect(20, 20, 120, 120),
			 this,
			 0x118);

    return TRUE;  // return TRUE  unless you set the focus to a control
}

A newly added list box appears as a rectangular empty box with a white background.

Practical LearningPractical Learning: Creating a List Box

  1. Design the dialog box as follows:
     
    Measures of Center
     
    Control Caption ID Align Text
    Static Text Static Text Value (x):    
    Edit Box Edit Control   IDC_VALUE Right
    Button Button Add IDC_ADD  
    List Box Button   IDC_VALUES  
    Button Button Reset IDC_RESET  
    Static Text Static Text Count:    
    Edit Box Edit Control   IDC_COUNT Right
    Static Text Static Text Sum:    
    Edit Box Edit Control   IDC_SUM Right
    Static Text Group Box Mean:    
    Edit Box Edit Control   IDC_MEAN  
    Button Button Close IDCANCEL  
  2. Right-click each of the edit controls and click Add Variable...
  3. Create the variables as follows:
     
    ID
    Category Type Name
    IDC_VALUE Value double m_Value
    IDC_VALUES Control CListBox m_Values
    IDC_COUNT Value int m_Count
    IDC_SUM Value double m_Sum
    IDC_MEAN Value double m_Mean
  4. In the Class View, expand the project and, in the top part, double-click CMeasuresOfCenter1Dlg
  5. Declare a CList variable named Values and that takes double as parameter:
    // MeasuesOfCenter1Dlg.h : header file
    //
    
    #pragma once
    #include "afxwin.h"
    
    // CMeasuesOfCenter1Dlg dialog
    class CMeasuesOfCenter1Dlg : public CDialogEx
    {
    // Construction
    public:
    	CMeasuesOfCenter1Dlg(CWnd* pParent = NULL);// standard constructor
    
    // Dialog Data
    	enum { IDD = IDD_MEASUESOFCENTER1_DIALOG };
    
    	protected:
    	virtual void DoDataExchange(CDataExchange* pDX);// DDX/DDV support
    
    
    // Implementation
    protected:
    	HICON m_hIcon;
    
    	// Generated message map functions
    	virtual BOOL OnInitDialog();
    	afx_msg void OnPaint();
    	afx_msg HCURSOR OnQueryDragIcon();
    	DECLARE_MESSAGE_MAP()
    public:
    	double m_Value;
    	CListBox m_Values;
    	int m_Count;
    	double m_Sum;
    	double m_Mean;
    
    private:
    	CArray<double, double> Values;
    };
  6. To execute and preview the dialog box, press F5
  7. Close the dialog box and return to your programming environment

Operations on a List Box

 

Adding a String to a List Box

After creating a list box, you can add items to it. This is done by calling the AddString() member function of the CListBox class. Its syntax is:

int AddString(LPCTSTR lpszItem);

This member function expects a null-terminated string as argument and adds this argument to the control. To add more items, you must call this member function for each desired item. Here is an example:

BOOL CExerciseDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);			// Set big icon
    SetIcon(m_hIcon, FALSE);		// Set small icon

    // TODO: Add extra initialization here
    m_CollegeMajors.AddString(L"Biology");
    m_CollegeMajors.AddString(L"Accounting");
    m_CollegeMajors.AddString(L"Art Education");
    m_CollegeMajors.AddString(L"Finance");
    m_CollegeMajors.AddString(L"Computer Science");

    return TRUE;  // return TRUE  unless you set the focus to a control
}

The items of a list box are arranged as a zero-based array. The top item has an index of zero. The second item as an index of 1, etc. Although the items seem to be added randomly to the list, their new position depends on whether the list is sorted or not. If the list is sorted, each new item is added to its alphabetical position. If the list is not sorted, each item is added on top of the list as if it were the first item. The other items are then "pushed down".

The Number of Strings in a List Box

At any time, if you want to know the number of items that a list box holds, call the GetCount() member function of the CListBox class. Its syntax is:

int GetCount() const;

This member function simply returns a count of the items in the list. Here is an example of calling it:

BOOL CExerciseDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);			// Set big icon
    SetIcon(m_hIcon, FALSE);		// Set small icon

    // TODO: Add extra initialization here
    m_CollegeMajors.AddString(L"Biology");
    m_CollegeMajors.AddString(L"Accounting");
    m_CollegeMajors.AddString(L"Art Education");
    m_CollegeMajors.AddString(L"Finance");
    m_CollegeMajors.AddString(L"Computer Science");

    m_Count = m_CollegeMajors.GetCount();
    UpdateData(FALSE);

    return TRUE;  // return TRUE  unless you set the focus to a control
}

This would produce:

List Box

Practical LearningPractical Learning: Populating a List Box

  1. On the main menu, click Project -> Class Wizard...
  2. In the Class Name combo box, select CMeasuresOfCenter1Dlg.
    Click Methods
  3. Click Add Method...
  4. Set the Return Type to void
  5. Set the Function Name to ShowValues
     
    Add Method
  6. Click OK
  7. Click Commands
  8. In the Commands list, click IDC_ADD
  9. Click Add Handler...
  10. Accept the suggested name of the function and click OK
  11. Click Edit Code
  12. Implement the event as follows:
    void CMeasuesOfCenter1Dlg::ShowValues(void)
    {
    	UpdateData();
    	double Sum = 0, Mean, Median;
    	CString strValue;
    
    	// Check the values in the collection
    	for(int i = 0; i < Values.GetCount(); i++)
    	{
    	    // Calculate the sum of values
    	    Sum += Values[i];
    
    	    // Since the value is a double, first convert it to a CString, ...
    	    strValue.Format(_T("%.3f"), Values[i]);
    	    // then add the string to the list box
    	    m_Values.AddString(strValue);
    
    	}
    
    	// Calculate the average
    	Mean = Sum / Values.GetCount();
    
    	// Display the values in the edit boxes
    	m_Count = m_Values.GetCount();
    	m_Sum = Sum;
    	m_Mean = Mean;
    	UpdateData(FALSE);
    }
    
    void CMeasuesOfCenter1Dlg::OnClickedAdd()
    {
    	// TODO: Add your control notification handler code here
    	UpdateData();
    	// Get the new value and store it in the collection
    	Values.Add(m_Value);
    
    	// Reset the Value edit box
    	m_Value = 0;
    	UpdateData(FALSE);
    	// Display the values
    	ShowValues();
    }

Inserting a String Into a List Box

Inserting a string consists of putting inside the list in a position of your choice. To support this operation, the CListBox class is equipped with the InsertString() member function whose syntax is:

int InsertString(int nIndex, LPCTSTR lpszItem);

The lpszItem argument is the string to be added to the list. The nIndex argument specifies the new position in the zero-based list. Here is an example:

BOOL CExerciseDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);			// Set big icon
    SetIcon(m_hIcon, FALSE);		// Set small icon

    // TODO: Add extra initialization here
    m_CollegeMajors.AddString(L"Biology");
    m_CollegeMajors.AddString(L"Accounting");
    m_CollegeMajors.AddString(L"Art Education");
    m_CollegeMajors.AddString(L"Finance");
    m_CollegeMajors.AddString(L"Computer Science");

    m_CollegeMajors.InsertString(1, L"Criminal Justice");

    m_Count = m_CollegeMajors.GetCount();
    UpdateData(FALSE);

    return TRUE;  // return TRUE  unless you set the focus to a control
}

This would produce:

List Box

If you pass it as 0, the lpszItem item would be made the first in the list. If you pass it as -1, lpszItem would be added at the end of the list, unless the list is empty.

Deleting a String From a List Box

To delete an item from the list, pass its index to the DeleteString() member function of the CListBox class. Its syntax is:

int DeleteString(UINT nIndex);

For example, to delete the second item of the list, pass a 1 value to this member function.

Clearing a List Box

If you want to delete all items of the control, call the ResetContent() member function of the CListBox class. Its syntax is:

void ResetContent();

This member function simply dismisses the whole content of the list box.

Practical LearningPractical Learning: Resetting a List Box

  1. Call the CListBox::ResetContent() member function at the beginning of the ShowValues() member function:
    void CMeasuesOfCenter1Dlg::ShowValues(void)
    {
        UpdateData();
        double Sum = 0, Mean, Median;
        CString strValue;
    
        // Clear the list box before populating it with strings from the collection
        m_Values.ResetContent();
    
        // Check the values in the collection
        for(int i = 0; i < Values.GetCount(); i++)
        {
    	// Calculate the sum of values
    	Sum += Values[i];
    
    	// Since the value is a double, first convert it to a CString, ...
    	strValue.Format(_T("%.3f"), Values[i]);
    	// then add the string to the list box
    	m_Values.AddString(strValue);
        }
    
        // Calculate the average
        Mean = Sum / Values.GetCount();
    
        // Display the values in the edit boxes
        m_Count = m_Values.GetCount();
        m_Sum = Sum;
        m_Mean = Mean;
        UpdateData(FALSE);
    }
  2. To execute, press F5
  3. Type each of the following values and click Add after each: 72604, 7592, 6314, 57086, 24885
     
    Measures of Center
  4. Close the dialog box and return to your programming environment

Selecting an Item From a List Box

Once a list has been created, you and your users can use its items. For example, to select an item, the user clicks it. To programmatically select an item (on a list box that allows only single selections), call the SetCurSel() member function of the CListBox class. Its syntax is:

int SetCurSel(int nSelect);

The nSelect argument specifies the item to select. To select the fourth item from a list box, you can pass the nSelect argument with a value of 3. Here is an example:

BOOL CExerciseDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);			// Set big icon
    SetIcon(m_hIcon, FALSE);		// Set small icon

    // TODO: Add extra initialization here
    m_CollegeMajors.AddString(L"Biology");
    m_CollegeMajors.AddString(L"Accounting");
    m_CollegeMajors.AddString(L"Art Education");
    m_CollegeMajors.AddString(L"Finance");
    m_CollegeMajors.AddString(L"Computer Science");

    m_CollegeMajors.InsertString(1, L"Criminal Justice");

    m_CollegeMajors.SetCurSel(3);

    m_Count = m_CollegeMajors.GetCount();
    UpdateData(FALSE);

    return TRUE;  // return TRUE  unless you set the focus to a control
}

If an item is selected in the list and you want to find out which one, you can call the GetCurSel() member function of the CListBox class. Its syntax is:

int GetCurSel() const;

Here is an example of calling it:

void CExerciseDlg::OnBnClickedGetSelection()
{
	// TODO: Add your control notification handler code here
	m_Selected = m_CollegeMajors.GetCurSel();
	UpdateData(FALSE);
}

This would produce:

List Box

As you can see, the CListBox::GetCurSel() member function returns the index of the string that was selected. If you want to get the actual string, you can call the GetText() member function of the CListBox class. It is overloaded with two versions whose syntaxes are:

int GetText(int nIndex, LPTSTR lpszBuffer) const;
void GetText(int nIndex, CString& rString) const;

The first argument represents the index of the item whose string you want to find out. The second argument is the returned string. Here is an example that returns a CString value by using the second version of the function:

void CExerciseDlg::OnBnClickedGetSelection()
{
    // TODO: Add your control notification handler code here
    m_CollegeMajors.GetText(m_CollegeMajors.GetCurSel(), m_Selected);
    UpdateData(FALSE);
}

Here is an example of running it:

List Box

     
 
 
 

Characteristics of a List Box

 

Single Selection of Items

After creating the list box, the user can select an item by clicking it in the list. The newly selected item becomes highlighted. Here is an example:

List Box

If the user clicks another item, the previous one looses its highlighted color and the new item becomes highlighted.

By default, the user can select only one item at a time. The ability to select one or more items is controlled by the Selection property in the Properties window:

Selection

The default value of the Selection field is Single. If you don't want the user to be able to select any item from the list, you have two main alterrnatives. If you set the Selection property to None, when the user clicks an item, a rectangle is drawn around the item but the highlighted color is not set. Alternatively, you can create the control with the Disabled property set to True.

Multiple-Selection

If you want the user to be able to select more than one item, at design time, set the Selection property to Multiple. If you are programmatically creating the control, add the LBS_MULTIPLESEL style. When a list box is created with the Multiple Selection option, to select an item, the user would click it. To select an additional item, the user can click it subsequently. If the user clicks an item that is highlighted, meaning it was already selected, the item becomes selected, loosing its highlighted color. The user can continue using this feature to build the desired list.

Extended Selection

Microsoft Windows allows a user to select items in a list box (in fact on many other list-based controls or views) by using a combination of mouse click and the keyboard. To select items in a range, the user can press and hold Shift, then click an item from the other range and release Shift. All items between both clicks would be selected. To select items at random, the user can press and hold Ctrl. Then click each desired item, which creates a series of cumulative selections. Here is an example:

List Box

To provide this ability, at design time, you can set the Selection property to Extended. If you are programmatically creating the list box, add the LBS_EXTENDEDSEL style to it.

Sorting a List Box

When building the list of items of a list box, by default, the items are rearranged in alphabetical order. Even if you add an item to an already created list, the new item is added to the right order. This arrangement means that the list is sorted. If you want the items to keep their position as they are added, set the Sort property to True. The ability to sort a list box or not is controlled by the LBS_SORT style.

It is important to remember that the list box treats its items as strings. Therefore, if your list box contains numeric values or dates (or times) and you sort it, the result may not appear incremental.

List Box Messages and Events

In order to use the list box as a control, it must first receive focus. This can be visible by either the first item having a rectangle drawn around it or at least on the items being selected. When the list box receives focus, it sends the LBN_SETFOCUS notification message. On the other hand, once the user clicks another control or another application, the list box loses focus and consequently sends the LBN_KILLFOCUS notification message.

As clicking is the most performed action on a list box, when the user clicks an item, it becomes selected. If the user clicks another item of a non-Multiple Selection list box, as the selection is going to be changed, the LBN_SELCHANGE notification message is sent. If the selection is cancelled, the LBN_SELCANCEL notification message is sent.

If the user double-clicks an item in the list box, the LBN_DBLCLK notification message is sent.

 
 
   
 

Home Copyright © 2010-2016, FunctionX