CListbox 绑定数据库

以下是源代码

1)CListBox* g_pListRecord;

2)g_pListRecord = (CListBox *)GetDlgItem(IDC_LIST_Record);

3)

int DBConnection::ReadItemInfo()
{
g_tLog.print("readListbox fo ItemInfo \n");
long nRecordId = 0;
if (m_bDBOpened == FALSE)
m_bDBOpened=OpenDB();
if (m_bDBOpened == FALSE)
{
g_tLog.print("OpenDB fail.\n");
return -1;
}
long nRet=0;
char sql[1024];
sprintf(sql,"select * from HOS_ITEM");
try
{
_CommandPtr pCmd;
pCmd.CreateInstance(__uuidof(Command));
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText =_bstr_t(sql);
pCmd->Parameters->Refresh();
pCmd->CommandType = adCmdText;
_RecordsetPtr pRs=pCmd->Execute(NULL,NULL,adCmdText);
if (pRs->GetState() == adStateClosed ||pRs->adoEOF)
return -1;




int nIndex=0;
ItemInfo *item;


while (pRs->GetState() != adStateClosed && !pRs->adoEOF)//
{
char ID[256],Name[256];
CString strTemp="";
_variant_t var;


//ID
var.Clear();
strTemp.Empty();
var=(LPTSTR)_bstr_t(pRs->GetCollect(L"ID"));
if (var.vt!=VT_NULL&&var.vt!=VT_EMPTY)
{
strTemp=(LPTSTR)_bstr_t(var);
strTemp.TrimLeft();
strTemp.TrimRight();
}
lstrcpy(ID, strTemp);






//Name
var.Clear();
strTemp.Empty();
var=(LPTSTR)_bstr_t(pRs->GetCollect(L"Name"));
if (var.vt!=VT_NULL&&var.vt!=VT_EMPTY)
{
strTemp=(LPTSTR)_bstr_t(var);
strTemp.TrimLeft();
strTemp.TrimRight();
}
lstrcpy(Name, strTemp);




char result[1024];
sprintf(result,"%20s%20s",ID,Name);


item=new ItemInfo;
item->ID=atol(ID);
strcpy(item->Name,Name);
g_tLog.print("ID[%d]Name[%s]\n",item->ID,item->Name);
g_pListItemInfo->SetItemData(nIndex,(DWORD_PTR)item);



nIndex++;


pRs->MoveNext();


}
pRs->Close();
pRs.Release();
}
catch (_com_error& e)
{
CloseDB();
g_tLog.print("com_error:%s,%s\n",(LPTSTR)e.Description(),sql);
return -1;
}
catch (...)
{
CloseDB();
g_tLog.print("error:%s,%s\n","出错,关闭数据库",sql);
return -1;
}
return nRecordId;//nRet;




}


其中要注意点:int nIndex=0; 必须从0开始才有效,记得在循环体里面加nIndex++;

其次, g_pListItemInfo->AddString(result);后再g_pListItemInfo->SetItemData(nIndex,(DWORD_PTR)item);

最后取数据:ItemInfo *item=(ItemInfo*)g_pListItemInfo->GetItemData(nIndex);g_tLog.print("选中id[%d]\n",item->ID);


你可能感兴趣的:(listbox)