MFC列表控件用ADO添加数据实例

1、本程序基于前期我的博客文章《MFC用ADO连接ACESS数据库实例(免费源码下载)》

程序功能通过编辑框、组合框实时将数据写入ACESS数据库并在列表控件上显示。

2、在主界面资源视图上加上一个按钮控件、两个静态文本、一个编辑框IDC_EDIT1变量名name、一个组合框IDC_COMBO1变量名COMBO。


3、在DataAdoDlg.h类定义中添加代码

cpp 复制代码
public:
void OnInitADOConn();
void display();
void ExitConnect();

4、DataAdoDlg.cpp中主要代码如下:

cpp 复制代码
BOOL CDataAdoDlg::OnInitDialog()
{
	CDialog::OnInitDialog();   
	......
	// TODO: Add extra initialization here
	m_COMBO.SetCurSel(0);  
	m_list.SetExtendedStyle(LVS_EX_FLATSB
		|LVS_EX_FULLROWSELECT
		|LVS_EX_HEADERDRAGDROP
		|LVS_EX_ONECLICKACTIVATE
		|LVS_EX_GRIDLINES);
  	m_list.InsertColumn(0,"姓名",LVCFMT_LEFT,50,0);
	m_list.InsertColumn(1,"性别",LVCFMT_LEFT,50,1);
	display();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDataAdoDlg::display()
{
	OnInitADOConn();
	//设置查询字符串
	_bstr_t bstrSQL = "select * from 表1 ";
	//创建记录集指针对象实例
	m_pRecordset.CreateInstance(__uuidof(Recordset));
	//打开记录集
	m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,
		adLockOptimistic,adCmdText);
	while(!m_pRecordset->adoEOF)
	{
		m_list.InsertItem(0,"");
    	m_list.SetItemText(0,0,(char*)(_bstr_t)m_pRecordset->GetCollect("姓名"));
		m_list.SetItemText(0,1,(char*)(_bstr_t)m_pRecordset->GetCollect("性别"));
		//将记录集指针移动到下一条记录
		m_pRecordset->MoveNext();
	}
	//关闭记录集和连接
ExitConnect();
}

void CDataAdoDlg::ExitConnect()
{
	//关闭记录集和连接
	if(m_pRecordset!=NULL)
		m_pRecordset->Close();
	m_pConnection->Close();
}


void CDataAdoDlg::OnButton1() 
{
UpdateData(TRUE);
	if(name.IsEmpty())
	{
		MessageBox("姓名不能为空!");
		return;
	}
	OnInitADOConn();
	_bstr_t sql;
	sql = "select * from 表1";
	m_pRecordset.CreateInstance(__uuidof(Recordset));
	m_pRecordset->Open(sql,m_pConnection.GetInterfacePtr(),adOpenDynamic,
		adLockOptimistic,adCmdText);
	try
	{
		m_pRecordset->AddNew(); //添加新行
		m_pRecordset->PutCollect("姓名",(_bstr_t)name);
		CString strWeb;   
        int nSel;     
        nSel = m_COMBO.GetCurSel();// 获取组合框控件的列表框中选中项的索引     
        m_COMBO.GetLBText(nSel, strWeb);  // 根据选中项索引获取该项字符串  
		m_pRecordset->PutCollect("性别",(_bstr_t)strWeb);
		m_pRecordset->Update(); //更新数据表
		ExitConnect();
	}
	catch(...)
	{
		MessageBox("操作失败");
		return;
	}
	MessageBox("添加成功");
	m_list.DeleteAllItems(); //删除列表控件
	display();			
}

运行程序

相关推荐
利刃大大4 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
C语言小火车5 小时前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle5 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです5 小时前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
Want5956 小时前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客6 小时前
c++ 杂记
开发语言·c++
jimmy.hua6 小时前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
tan180°6 小时前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
bkspiderx7 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
郝学胜-神的一滴7 小时前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生