c++visual-studiomfcclistbox

MFC CListBox.AddString() doesn't show string


I am creating an MFC application and trying to add list box in the dialog class. When I use debug configuration, it gets error and application crashes. When I use release configuration, the dialog shows up, but is empty.

I just started with this, so my code is basic:

//code... (it is including #include "MyDialog.h") 

CMyDialog dialog; //CMyDialog includes public CListBox variable m_listBox
CString str;
str = L"Hello";
dialog.m_listBox.AddString(str);
dialog.DoModal();

//code...

But it doesn't work anyway.

In debug configuration I get this message: "Debug Assertion failed!" Debug Assertion failed!

In release configuration the dialog is empty (instead of having a line with 'Hello'):

MyDialog:

MyDialog.

The error occures right in the moment of calling AddString() function and it happens even when this function is called right in CMyDialog class (for example I tried to call it in the constructor).

I would like to know what I am doing wrong, I suppose that the problem isn't in dialog class itself, but somewhere else. I tried to search through the internet, but I found no solution, so I am here :)


Solution

  • What you are doing wrong is trying to use a member (m_listBox) too early. Members that are dialog controls, as opposed to non-window types like a CString member, are only in a state to be used once the dialog has been invoked with DoModal().

    Assertions are debug macros which is why you get no indication of the problem in Release configuration.

    The correct place to populate a listbox control will typically be the OnInitDialog override member function. The dialog then has been invoked by that stage, and controls owned by the dialog will have window handles and can be used.

    If you are specifically wanting to pass the string literal to the dialog from before invoking the dialog then you can have the CString as a member variable of the dialog class. Such a member exists upon construction of the class instance, and can be set via the constructor, or a public setter, or by having public accessibility.