Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Visual C++ and MFC Fundamentals Chapter 20: List-Based Controls


ResizeParentToFit();

m_ListOfStudents.AddString("Jules Nsang");
m_ListOfStudents.AddString("George Young");
m_ListOfStudents.AddString("Christine Larson");
m_ListOfStudents.AddString("James Carlton");
m_ListOfStudents.AddString("Annette Simms");
m_ListOfStudents.AddString("Ernestine Whitfield");
m_ListOfStudents.AddString("Paulin Ngono");
m_ListOfStudents.AddString("Lester Gramms");
m_ListOfStudents.AddString("Daniella Parent");
m_ListOfStudents.AddString("Hermine Krantz");
m_ListOfStudents.AddString("Faustin Nguyen");
}

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”. If the list is not sorted, you can add an item in the position of your
choice. This is done using the CListBox::InsertString() method 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. 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.

Based on this, to delete an item from the list, pass its index to the
CListBox::DeleteString() method. Its syntax is:

int DeleteString(UINT nIndex);
Free download pdf