Click to See Complete Forum and Search --> : Problem on list box control


elliottso
January 23rd, 2006, 09:35 PM
Hi,

The following code tries to put an owner defined class object, CAccountInfo, into the list box control.
CAccountInfo *userAccount=new CAccountInfo();
userAccount->username=t_username;
userAccount->ip=t_ip;
userAccount->status=t_status;
userAccount->nat=t_nat;

if(!strcmp(a_status.m_psz,"online")){
userAccount->statusPic = LoadBitmap(this->inst, MAKEINTRESOURCE(IDB_LOGO_ONLINE));
// add a string to the list box so that item can be set
SendMessage(GetDlgItem(HDialogBuddy, IDC_ONLINELIST), LB_ADDSTRING, 0, (LPARAM)"a");
int endOfList = (int)SendMessage(GetDlgItem(HDialogBuddy, IDC_ONLINELIST), LB_GETCOUNT, 0, 0);
SendMessage(GetDlgItem(HDialogBuddy, IDC_ONLINELIST), LB_SETITEMDATA, endOfList-1, (LPARAM)userAccount);
}
When the program receives the WM_DRAWITEM, I get back the object.
case WM_DRAWITEM:
lpdis = (LPDRAWITEMSTRUCT) lParam;
// If there are no list box items, skip this message.
if (lpdis->itemID == -1)
{
break;
}
switch (lpdis->itemAction)
{
case ODA_DRAWENTIRE:
{
CAccountInfo *account = (CAccountInfo*)malloc(sizeof(CAccountInfo*));
account = (CAccountInfo*)SendMessage(lpdis->hwndItem, LB_GETITEMDATA, lpdis->itemID, (LPARAM) 0);
// access violation occurs stating that I am reading a null pointer on the following line
MessageBox(0, account->username, 0, 0);
free(account);
break;
}
}
I would like to ask why I cannot get back the object successfully?
Thank you!

NoHero
January 24th, 2006, 02:31 AM
CAccountInfo *account = (CAccountInfo*)malloc(sizeof(CAccountInfo*));
account = (CAccountInfo*)SendMessage(lpdis->hwndItem, LB_GETITEMDATA, lpdis->itemID, (LPARAM) 0);
// access violation occurs stating that I am reading a null pointer on the following line
MessageBox(0, account->username, 0, 0);
free(account);
break;

That's basic C. I suggest you to grab a book and learn pointers from the beginning again. You are allocating a memory block in the size of a pointer, which is actually not needed!

CAccountInfo *account = (CAccountInfo*)SendMessage(lpdis->hwndItem, LB_GETITEMDATA, lpdis->itemID, (LPARAM) 0);

Does your trick...

elliottso
January 24th, 2006, 03:11 AM
Thank you, NoHero!
I have modified the problem already. I am sorry for posting a stupid thread.
PS I have started writing windows programming for four months only. :blush: