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

运行程序

相关推荐
旖旎夜光7 分钟前
list实现(7)(上)
c++
不会c嘎嘎17 分钟前
深入理解 C++ 异常机制:从原理到工程实践
开发语言·c++
崇山峻岭之间29 分钟前
C++ Prime Plus 学习笔记026
c++·笔记·学习
赖small强2 小时前
【Linux C/C++开发】Linux 平台 Stack Protector 机制深度解析
linux·c语言·c++·stack protector·stack-protector·金丝雀机制
Wild_Pointer.2 小时前
环境配置指南:全景目录
c++
疋瓞2 小时前
C++_win_QT6学习《3》_结合qt项目开发学习git仓库相关知识
c++·qt·学习
minji...3 小时前
Linux 基础IO(一) (C语言文件接口、系统调用文件调用接口open,write,close、文件fd)
linux·运维·服务器·网络·数据结构·c++
第二只羽毛3 小时前
C++ 高性能编程要点
大数据·开发语言·c++·算法
崇山峻岭之间3 小时前
C++ Prime Plus 学习笔记027
c++·笔记·学习
赖small强4 小时前
【Linux C/C++开发】Linux C/C++ 堆栈溢出:原理、利用与防护深度指南
linux·c语言·c++·stack·堆栈溢出