I am trying to populate a ListBox with data I am reading from a text file, but have had no luck. I tried several ways to do SendMessage
(please see below) but get the same "invalid cast type" error.
ListBox:
CreateWindow("listbox", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL|
LBS_NOTIFY, 20, 90, 200, 365,
hwnd, (HMENU)LST_LISTBOX, NULL, NULL);
I keep on changing the SendMessage
:
SendMessage(LST_LISTBOX, LB_INSERTSTRING, 0, (LPARAM)10); //myline[i]);
SendMessage(LST_LISTBOX, LB_ADDSTRING, 0, (LPARAM) myline[i]);
SendMessage(GetDlgItem(hwnd, LST_LISTBOX), LB_ADDSTRING, 0, (LPARAM) myline[i] );
What would be the best way to populate a listbox from a file?
You need to send the message to the HWND
that CreateWindow()
creates. You can get that from the return value of CreateWindow()
, or from GetDlgItem()
after CreateWindow()
is finished.
The LPARAM
for LB_ADDSTRING
and LB_INSERTSTRING
needs to be a pointer to the 1st character of a null-terminated C-style string, eg:
char myline[size];
//fill myline as needed...
HWND hwndLB = CreateWindowA(WC_LISTBOXA, ... hwnd, reinterpret_cast<HMENU>(LST_LISTBOX), ...);
// or:
// CreateWindowA(...);
// HWND hwndLB = GetDlgItem(hwnd, LST_LISTBOX);
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline));
Alternatively:
std::string myline;
//fill myline as needed...
HWND hwndLB = ...;
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline.c_str()));
UPDATE: based on comments you posted, myline
seems to be a std::string[20]
array, so you need to index into the array and call c_str()
on the desired element, eg:
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline[i].c_str()));