List Control is one of the useful controls to display data in
different formats viz., icon view, report view, simple list
etc., This article describes how to use CListCtrl for creating
report views.
Before using any control resources in MFC, they must be
associated with a class. Use the Member Variable tab of the
Class Wizard to create a variable for the List Control. This
CListCtrl variable will be used subsequently for our
samples. Make sure that the property of Report is
selected for view under style tab
of the properties box. Also the stdafx.h file should have
afxcmn.h included.
CListCtrl
- Inserting Columns:
There are many different signatures of InsertColumn function
to this operation. But this article use the simplest of all.
int InsertColumn( int nCol, LPCTSTR lpszColumnHeading,
int nFormat = LVCFMT_LEFT, int nWidth
= -1, int nSubItem = -1 );
nCol :
This specifies the position of the columns, starting from 0.
lpszColumnHeading
: The string specified here will be considered as the Header
Row for the list control.
nFormat
: For alignments. LVCFMT_LEFT for left, LVCFMT_RIGHT for right
and LVCFMT_CENTER for Center.
nWidth :
Width in pixels.
Look at the following sample usage for the InsertColumn
function.
m_ListVw.InsertColumn(0, "Heading 1",LVCFMT_LEFT,
100);
m_ListVw.InsertColumn(1, "Heading
2",LVCFMT_LEFT, 120);
This will add two column headings to the List control as Heading1
and Heading2.
CListCtrl
- Adding Rows:
Adding
Row for a Single Column List Control:
Adding rows if the control has a single column, will be
straightforward. It is enough if we call InsertItem function
as below.
m_ListVw.InsertItem(0,"Item1");
m_ListVw.InsertItem(1,"Item2");
The first parameter is the row number of the CListCtrl. This
is a number starting from 0. The InsertItem functions returns
an index, which can be used to call other functions to operate
on the row.
Adding
Rows for a Multi column CListCtrl:
This will need usage of two functions viz., InsertItem and
SetItemText as follows.
int nIndex = m_ListVw.InsertItem(0,"Item1");
m_ListVw.SetItemText(nIndex,1,"Item12");
m_ListVw.SetItemText(nIndex,2,"Item12");
There are more ways of adding items to the list controls. But
this one is probably the simplest. The function SetItemText
can also be used to modify the data inside a cell.
CListCtrl
- Deleting Rows:
If one wants to delete all the rows in the List control, the
function DeleteAllItems should be used. If someone
wants to delete item wise, the function DeleteItem
should be called. The following is the sample piece of code
for it.
m_ListVw.DeleteItem(2);
The above code will delete the 3rd row from the list control.
This parameter specifies the Row index starting from 0.
CListCtrl - Reading an
item from a Row:
This article assumes the item read is the currently selected item.
int nSelected = m_ListVw.GetSelectionMark();
CString strText = m_ListVw.GetItemText(nSelected,
0);
This retrieves the value from the nSelected row and first
column.