List Box Example

When not to use list boxes:

1.  When there are few choices and they are known at compile time. Then you should use radio buttons.

2.  When there are hundreds of choices. Then the choices should be organized better.

When to use list boxes:

1.  When the choices are not known at compile time. Example: What is the independent variable ? (in a mathematical expression to be graphed).

For an example of how to use list boxes, we will make a dialog with an edit box where you can type something, and an Add button, which adds the contents of the edit box to a list, and a list box which allows you to select an item, and a Delete button which will delete the selected item.

For simplicity we base the program on CFormView.

Here’s the dialog in the dialog editor:



Notice that you cannot initialize any strings in the list box from the Dialog Editor. You must do this, using the list box’s AddString method, in OnInitDialog.

Now, we need to add code for the Add button, which will get the text from the edit box and add it to the list box. We need to associate a CString variable with the edit box, and use its contents to fetch the edit box text, and then call the list box’s AddString method.

Rather than use GetDlgItem each time we need the list box, we associate a control variable to the list box, using class wizard. Then we can use that member variable, which will be of type CListBox, to access the list box and hence its methods. (In essence, MFC will call GetDlgItem to initialize this variable.)

Bring up Class Wizard from the dialog editor:


Click Add Variable and select Control from the Category edit box:


Add a variable m_Editbox for the edit box--but it is of category Value.

Use Class Wizard to add functions OnAdd and OnDelete for your two buttons.


Initializing the list box.

Since our program is based on CFormView, we won’t have OnInitDialog. Instead we have OnInitialUpdate.

void CListExampleView::OnInitialUpdate()

{

CFormView::OnInitialUpdate();

GetParentFrame()->RecalcLayout();

ResizeParentToFit();

m_ListBox.AddString("cat");

m_ListBox.AddString("dog");

m_ListBox.AddString("giraffe");

}

(Light shading shows what AppWizard wrote; dark shading, what we must write. When these notes appear on the Web no shading survives--it is the AddString lines that we had to write.)

It works:



Here’s the button-handler code:

void CListExampleView::OnAdd()

{

UpdateData(TRUE);

m_ListBox.AddString(m_Editbox);

}

void CListExampleView::OnDelete()

{

m_ListBox.DeleteString(m_ListBox.GetCurSel());

}

Note the UpdateData(TRUE). Without it, the Add button doesn’t work, because the variable m_Editbox won’t contain the contents of the edit box.



Note that “aardvark” was added to the beginning of the list. Look at the property sheet of the list box. The “sorted” property is checked:



Deleting strings also works:


Now press Delete: