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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值