Sepideh Abadpour
Sepideh Abadpour

Reputation: 2598

How to add items to a List Control in an MFC dialog

In order to have a table like:

enter image description here
in my MFC dialog, I have added a List Control to it. And then with Add Variable wizard, I have created this variable for the control:

public:
CListCtrl m_lstIDC_LIST1Control;  

and then in the OnInitDialog function of my dialog, I have added these lines of code:

// TODO: Add extra initialization here
m_lstIDC_LIST1Control.SetExtendedStyle(LVS_EX_FULLROWSELECT);
m_lstIDC_LIST1Control.SetExtendedStyle(LVS_EX_GRIDLINES);
//m_lstIDC_LIST1Control.SetExtendedStyle( LVS_SHOWSELALWAYS);
LVITEM lvItem;

lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
char* text = "Sandra C. Anschwitz";
wchar_t wtext[50];
mbstowcs(wtext, text, strlen(text)+1);
LPWSTR ptr = wtext;
lvItem.pszText = ptr;
m_lstIDC_LIST1Control.InsertItem(&lvItem);
UpdateData(false);  

the result that I get is:

enter image description here
and if I uncomment the line:

//m_lstIDC_LIST1Control.SetExtendedStyle( LVS_SHOWSELALWAYS);  

the horizontal grids will not be shown either!
So what's the problem?
Why the item that I have added is not shown? what should I do in order to create a table like the one shown in the first picture?

Upvotes: 5

Views: 35861

Answers (2)

Swiss Frank
Swiss Frank

Reputation: 2422

Also make sure you've got the right kind of control... you want what (at least on Visual Studio 2008's Resource Editor) is called a List Control in the toolbox, not the List Box.

Upvotes: 2

Roger Rowland
Roger Rowland

Reputation: 26279

First, make sure you chose the Report option of the View property of the List Control in the Resource Editor. I suspect that you are using the default Icon view, which is not what you want.

Then, you need to add the required columns:

m_lstIDC_LIST1Control.InsertColumn(0, _T("Full Name"), LVCFMT_LEFT, 90);
m_lstIDC_LIST1Control.InsertColumn(1, _T("Profession"), LVCFMT_LEFT, 90);
m_lstIDC_LIST1Control.InsertColumn(2, _T("Fav Sport"), LVCFMT_LEFT, 90);
m_lstIDC_LIST1Control.InsertColumn(3, _T("Hobby"), LVCFMT_LEFT, 90);

Finally, you can populate your list items simply as follows:

int nIndex = m_lstIDC_LIST1Control.InsertItem(0, _T("Sandra C. Anschwitz"));
m_lstIDC_LIST1Control.SetItemText(nIndex, 1, _T("Singer"));
m_lstIDC_LIST1Control.SetItemText(nIndex, 2, _T("Handball"));
m_lstIDC_LIST1Control.SetItemText(nIndex, 3, _T("Beach"));

nIndex = m_lstIDC_LIST1Control.InsertItem(1, _T("Roger A. Miller"));
m_lstIDC_LIST1Control.SetItemText(nIndex, 1, _T("Footballer"));
m_lstIDC_LIST1Control.SetItemText(nIndex, 2, _T("Tennis"));
m_lstIDC_LIST1Control.SetItemText(nIndex, 3, _T("Teaching"));

And so on ....

Upvotes: 24

Related Questions