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

运行程序

相关推荐
lengxuenong4 分钟前
树状数组 · 信息学学习手册3-优化LIS
c++·学习·算法
fanfan_hongyun14 分钟前
【UE5.1 创建C++文件】
c++·ue5
余额瞒着我当琳21 分钟前
C++11,发展历史浅谈,初始化列表和对象初始化,右值引用和移动语义
java·开发语言·c++·算法
Tsuki_tl39 分钟前
【优选算法:双指针】——复写零题解
java·c++·算法·leetcode·数组·双指针·复写零
程序猿编码1 小时前
不用 PyTorch!从零手写 C++ 深度学习框架,自动微分、CUDA、分布式一把搞定
c++·深度学习·大模型推理·自动微分
real_metrix1 小时前
【学习笔记】C/C++ 头文件自包含
c++·c·头文件·自包含
雪落漂泊1 小时前
C++算法 滑动窗口篇(上)
开发语言·c++·算法
像枫一样1 小时前
STM32串口轮询收发实战教程
arm开发·c++·stm32·单片机·嵌入式硬件·fpga开发·51单片机
Soneswy1 小时前
C++基础篇——类与对象(上)
开发语言·c++
张小姐的猫1 小时前
【MySQL】表的约束
android·linux·服务器·数据库·c++·mysql·adb