Click here to Skip to main content
15,880,469 members
Articles / Desktop Programming / ATL

Using MS DataGrid control with OLE DB consumer

Rate me:
Please Sign up or sign in to vote.
4.25/5 (8 votes)
22 Sep 20013 min read 189.5K   2.1K   37  
Use the MS DataGrid control in your C++ app with OLE DB Consumer Templates
// LeftView.cpp : implementation of the CLeftView class
//

#include "stdafx.h"
#include "MSDataGrid.h"

#include "MSDataGridDoc.h"
#include "LeftView.h"
#include "MainFrm.h"
#include "DataGridView.h"
#include "atldbsch.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CLeftView

IMPLEMENT_DYNCREATE(CLeftView, CTreeView)

BEGIN_MESSAGE_MAP(CLeftView, CTreeView)
	//{{AFX_MSG_MAP(CLeftView)
	ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnSelchanged)
	//}}AFX_MSG_MAP
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, CTreeView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, CTreeView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, CTreeView::OnFilePrintPreview)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CLeftView construction/destruction

CLeftView::CLeftView()
{
	// TODO: add construction code here

}

CLeftView::~CLeftView()
{
	m_ImageSmall.DeleteImageList();
}

BOOL CLeftView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CTreeView::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CLeftView drawing

void CLeftView::OnDraw(CDC* pDC)
{
	CMSDataGridDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

	// TODO: add draw code for native data here
}


/////////////////////////////////////////////////////////////////////////////
// CLeftView printing

BOOL CLeftView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CLeftView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CLeftView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}

void CLeftView::OnInitialUpdate()
{
	CTreeView::OnInitialUpdate();

    m_ImageSmall.Create (16, 16, TRUE, 2, 1);

	HICON hIcon = AfxGetApp()->LoadIcon(IDI_ICON_TABLE);
	ASSERT(hIcon);

	m_ImageSmall.Add(hIcon);

    HICON hIconSub = AfxGetApp()->LoadIcon(IDI_ICON_TABLE_SUB);
	ASSERT(hIconSub);

	m_ImageSmall.Add(hIconSub);
}

/////////////////////////////////////////////////////////////////////////////
// CLeftView diagnostics

#ifdef _DEBUG
void CLeftView::AssertValid() const
{
	CTreeView::AssertValid();
}

void CLeftView::Dump(CDumpContext& dc) const
{
	CTreeView::Dump(dc);
}

CMSDataGridDoc* CLeftView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMSDataGridDoc)));
	return (CMSDataGridDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CLeftView message handlers
bool CLeftView::PopulateTree()
{
	// lets get the connection
    CMainFrame* pMainFrame = reinterpret_cast<CMainFrame*>(AfxGetMainWnd());
        
	GetTreeCtrl().SetImageList( &m_ImageSmall, TVSIL_NORMAL );
    
    HTREEITEM hTreeRoot;

    bool bRet = true;

    // delete all items from the tree
    GetTreeCtrl().DeleteAllItems();

    if (pMainFrame->m_bConnectionValid)
    {
	    try
	    {
            CTables tableSet;
            HRESULT hr = tableSet.Open(pMainFrame->m_session);
            if (SUCCEEDED(hr))
            {
			    CString sName, sNameShort, sSchema;
			    int nPos = -1;
			    HRESULT hr = S_OK;
			    int nIndex = 0;
			    
                hTreeRoot = GetTreeCtrl().InsertItem("Tables", 0, 0);

                while (tableSet.MoveNext() == S_OK)
                {
                    sName = tableSet.m_szName;
                    sNameShort = sName;
				    nPos = sName.Find(';');
				    if(nPos != -1)
					    sName = sName.Left(nPos);
				    if(sName.Find(' ') != -1) // MS SQL Server scenario
					   sName = "[" + sName + "]";
				    // Alternatively...

				    sSchema = tableSet.m_szSchema;

				    HTREEITEM hTreeSPRoot = GetTreeCtrl().InsertItem(sName, 1, 1, hTreeRoot);
                                    
                }                
            } 
            else
            {
				if(FAILED(hr))
					_com_issue_error(hr);
            }
	    }
	    catch(_com_error e)
	    {
		    bRet = false;
            AfxMessageBox(GetErrorDescription(e));
	    }
	    catch(...)
	    {
		    bRet = false;
		    AfxMessageBox("UnKnown Error");
	    }
    }

	GetTreeCtrl().Expand(hTreeRoot, TVE_EXPAND);
    return bRet;
}

void CLeftView::OnSelchanged(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	// TODO: Add your control notification handler code here

    // make sure we go in here only once
    static bool bDone(false);
    if (!bDone)
    {
        bDone = true;
        
        HTREEITEM hItem = GetTreeCtrl().GetSelectedItem();
        if ((hItem != NULL))
        {
            if(!GetTreeCtrl().ItemHasChildren(hItem))
            {
                CMainFrame* pMainFrame = reinterpret_cast<CMainFrame*>(AfxGetMainWnd());
                if (pMainFrame)
                {
                    CDataGridView* pRightView = reinterpret_cast<CDataGridView*>(pMainFrame->m_wndSplitter.GetPane(0,1));
                    CString sTableName = GetTreeCtrl().GetItemText(hItem);

                    if (pRightView)
                    {
                        // remove the schema name
                        int nPos(0);
                        if ((nPos = sTableName.Find('(')) != -1)
                        {
                            sTableName = sTableName.Left(sTableName.GetLength() - (sTableName.GetLength()-nPos));
                            sTableName.TrimRight();
                        }
                        pRightView->UpdateGridDetails(sTableName);
                    }
                }
            }
        }
        
        bDone = false;
    }
        
	*pResult = 0;
}

CString CLeftView::GetErrorDescription(_com_error& e)
{
    _bstr_t bstrSource(e.Source());
    _bstr_t bstrDescription(e.Description());
    _TCHAR szTemp[1024];

    CString strInfo ;
    wsprintf(szTemp, _T("Message : %s\n"), e.ErrorMessage());
    strInfo = szTemp;
    wsprintf(szTemp, _T("Code : 0x%08lx\n"), e.Error());
    strInfo += szTemp;
    wsprintf(szTemp, _T("Source : %s\n"), bstrSource.length() ? (LPCTSTR)bstrSource : _T("null"));
    strInfo += szTemp;
    wsprintf(szTemp, _T("Description : %s\n"), bstrDescription.length() ? (LPCTSTR)bstrDescription : _T("null"));
    strInfo += szTemp;

    return strInfo;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
Was made redundant in early 2003 after 10 years in computer programming, since then started my own business (selling computer books on the net)
www.pricecutbook.co.uk


Comments and Discussions