Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Database » Adding ODBC support to a new application

Adding ODBC support to a new application

This tutorial guides you to add CRecordview support to your MFC application. MFC AppWizard let you add ODBC support to your application by adding few simple extra steps.

Author Rank :
Page Views : 1915
Downloads : 49
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
AddViewSp.zip | add_odbc_view_supp.zip
 
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

This tutorial guides you to add CRecordview support to your MFC application. MFC AppWizard let you add ODBC support to your application by adding few simple extra steps.

Creating an ODBC DataSource

If you know how to create an ODBC Data Source then you can skip this part. Just create an ODBC Data Source with your database.

You need an ODBC Data Source to use ODBC in your application. You create ODBC data source from ODBC Administration. You can call ODBC Admin from Control Panel.



Click Add to create a new Data Source. You get this dialog. Select your database type. I have an access database so I pick Microsoft Access Driver (*.mdb).



Next dialog asks you to put Data Source Name and Description. You can pick any name as your Data Source Name and corresponding description. Next step is to call your database. If you don't have any database, create database with some tables and data in it. Or download access database mcb1.krz attached with this article.



Pick your database and click Ok. Close the ODBC Admin dialog.



Creating Skeleton of Your Application

MFC AppWizard adds ODBC support to your application by selecting option Database Support on AppWizard's page 2.
Create a new SDI application.



Select SDI Support.



Select Database view without file support option.



Select ODBC Data Source Name, which has you, created in very first step. Make sure you select Recordset type as dynaset.



Select a table from your database.



Leave other AppWizard options as default and Click Finish.



Build and Run the project. You should be able to run the project with no errors.

Under the Hood

Under the hood, AppWizard has added a class called CAddViewSpSet. This class is derived from CRecordset.

CAddViewSpSet class

CAddViewSpSet class is a CRecordset derived class. Declaration header file looks like this:

class CAddViewSpSet : public CRecordset
{
public:CAddViewSpSet(CDatabase* pDatabase = NULL);
DECLARE_DYNAMIC(CAddViewSpSet)
// Field/Param Data
//{{AFX_FIELD(CAddViewSpSet, CRecordset)
CString m_Template;
CString m_SearchName;
CString m_Search;
//}}AFX_FIELD
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAddViewSpSet)
public:
virtual CString GetDefaultConnect();
// Default connection stringvirtual CString GetDefaultSQL();
// default SQL for Recordsetvirtual void DoFieldExchange(CFieldExchange* pFX); // RFX support
//}}AFX_VIRTUAL
// Implementation
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
};

This class has a member variable corresponding to each column of table. Besides this, it has three pure virtual functions with a default constructor, AssertValid, and Dump function. Here is implementation of this class:

// CAddViewSpSet implementation
IMPLEMENT_DYNAMIC(CAddViewSpSet, CRecordset)
CAddViewSpSet::CAddViewSpSet(CDatabase* pdb): CRecordset(pdb)
{
//{{AFX_FIELD_INIT(CAddViewSpSet)
m_Template = _T("");
m_SearchName = _T("");
m_Search = _T("");
m_nFields = 3;
//}}AFX_FIELD_INIT
m_nDefaultType = dynaset;
}
CString CAddViewSpSet::GetDefaultConnect()
{
return _T("ODBC;DSN=mcbKruse");
}
CString CAddViewSpSet::GetDefaultSQL()
{
return _T("[Hunt]");
}
void CAddViewSpSet::DoFieldExchange(CFieldExchange* pFX)
{
//{{AFX_FIELD_MAP(CAddViewSpSet)
pFX->SetFieldType(CFieldExchange::outputColumn);
RFX_Text(pFX, _T("[Template]"), m_Template);
RFX_Text(pFX, _T("[SearchName]"), m_SearchName);
RFX_Text(pFX, _T("[Search]"), m_Search);
//}}AFX_FIELD_MAP}
//CAddViewSpSet diagnostics
#ifdef _DEBUG
void CAddViewSpSet::AssertValid() const
{
CRecordset::AssertValid();
}
void CAddViewSpSet::Dump(CDumpContext& dc) const
{
CRecordset::Dump(dc);
}
#endif //_DEBUG

GetDefaultConnect returns a string with ODBC Data Source name. You can change data source name if you don't want to use your old Data Source.

GetDefaultSQL returns the table name, which you are connected to.

DoFieldExchange binds table columns to the class's data members. See CRecordset class in MSDN for more details.

CAddViewSpDoc Class

Besides this, AppWizard has added a member variable in Doc class of application.

CAddViewSpSet m_addViewSpSet;

CAddViewSpView Class

View class of your application is derived from CRecordView now. See CRecordView for more details. View class has more additions than that. One variable of CRecordset* type has added to the view class of the project.

CAddViewSpSet* m_pSet;

Which is being initialized in the constructor:

CAddViewSpView::CAddViewSpView(): CRecordView(CAddViewSpView::IDD)
{
//{{AFX_DATA_INIT(CAddViewSpView)
// NOTE: the ClassWizard will add member initialization here
m_pSet = NULL;
//}}AFX_DATA_INIT
// TODO: add construction code here
}
OnInitialUpdate is overridden with this code:
void CAddViewSpView::OnInitialUpdate()
{
m_pSet = &GetDocument()->m_addViewSpSet;
CRecordView::OnInitialUpdate();
GetParentFrame()->RecalcLayout();
ResizeParentToFit();
}

and a new function OnGetRecordset has been added to the class which returns pointer to CRecorset.

CRecordset* CAddViewSpView::OnGetRecordset()
{   
return m_pSet;
}

Resource Additions

AppWizard has added a dialog template, one menu item 'Record' with four submenus and four tool bar buttons. We will see all these in our sample project.

Customizing The Project

Database support has been added to our application. Now let's customize the application according to our needs.

Add Controls to The Dialog

This is what my application will look like. MFC AppWizaed has added a dialog to your application. Go to Resources from ClassView and double click on newly added dialog. Add three edit fields, three static fields, a list box, and a button. Three exit boxes will show three fields of the table, which we can move by using menu or toolbar options.



FillList button click will add one column's data of the table to the list box.

Add Members

Add member variables corresponding to all three edit boxes by using ClassWizard. Click ClassWizard from the menu and select MEmber Variable Tab.



Now Click Add Variable button and add three variables corresponding to IDC_EDIT1, IDC_EDIT2, and IDC-EDIT3. Instead of adding new names, select m_pSet members from the drop-down list.



After adding these data members, your ClassWizard would look like this:



Now write a command handler for FillList button by double clicking it and write this code:

void CAddViewSpView::OnButton1()
{
CListBox* list = (CListBox*)GetDlgItem(IDC_LIST1) ;
list->ResetContent();
if ( m_pSet->IsEOF() && m_pSet->IsBOF() )
return;
m_pSet->MoveFirst();
while ( ! m_pSet->IsEOF() )
{
list->AddString( m_pSet->m_SearchName );
m_pSet->MoveNext();
}
m_pSet->MoveFirst();
UpdateData(FALSE);
}

Build and Run the application. Here is how output looks like:



Run The Applicaion

Download attached project zip file. Unzip the project file. Create a new datasource "mcbKruse" with your database. Create a new table called 'Hunt' with three fields in it, i.e. Template, Search Name and Search. If you have different field names then change to your field names in the CRecordset derived class. Build and run the application.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.