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

运行程序

相关推荐
朝朝辞暮i6 小时前
C++ 第 4 课:if / else —— 让程序自己做决定
开发语言·c++
苏打豆7 小时前
Pinocchio源码阅读——刚体运动物理量空间变换及求导
c++·线性代数·算法·矩阵·机器人
m0_380743877 小时前
Qt中导航栏实现的详细指南
开发语言·c++
估值探索者7 小时前
【Python量化策略实战 #02】多因子合成mom和vol两因子打分合成
开发语言·c++·python·数据挖掘·c#
思麟呀7 小时前
位运算:从一个整数到一个集合
c语言·数据结构·c++·算法
All for pursuit.8 小时前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
头发够用的程序员9 小时前
TensorRT 自定义算子插件实战(一):从零手写 customScaledTanh
c++·人工智能·pytorch·python·深度学习·边缘计算·jetson
哭泣方源炼蛊9 小时前
正则表达式c++内容汇集
数据库·c++·mysql·正则表达式
别动我齐刘海9 小时前
简历技术栈全面复习——UDP / TCP / CAN / ZMQ / Protobuf 通信工程
网络·c++·python·tcp/ip·机器学习·udp·github
All for pursuit.10 小时前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode