1、導入CGridCtrl類
2、在stdafx.h中包含GridCtrl.h
#include "GridCtrl_src/GridCtrl.h"
3、GridCtrlExampleDlg.h中定義CGridCtrl對象
CGridCtrl m_pGridCtrl;
4、GridCtrlExampleDlg.h中定義表格初始化函數OnInitialGrid()和一些用到的變量
void OnInitialGrid();
int m_nFixCols;
int m_nFixRows;
int m_nCols;
int m_nRows;
5、GridCtrlExampleDlg.cpp中實作OnInitialGrid()
void CGridCtrlExampleDlg::OnInitialGrid()
{
m_pGridCtrl.SetEditable(false);
m_nFixCols = 1;
m_nFixRows = 1;
m_nCols = 11;
m_nRows = 10;
TRY
{
m_pGridCtrl.SetRowCount(m_nRows);
m_pGridCtrl.SetColumnCount(m_nCols);
m_pGridCtrl.SetFixedRowCount(m_nFixRows);
m_pGridCtrl.SetFixedColumnCount(m_nFixCols);
m_pGridCtrl.SetHeaderSort();
m_pGridCtrl.SetCompareFunction(CGridCtrl::pfnCellNumericCompare);
m_pGridCtrl.EnableDragAndDrop();
}
CATCH (CMemoryException, e)
{
e->ReportError();
e->Delete();
return;
}
END_CATCH
char* GridColtable[]={"","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V",""};
int Gridwidth[]={40,80,80,80,80,80,80,90,90,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,100,100};
GV_ITEM Item;
int row=0;
Item.mask = GVIF_TEXT;
m_pGridCtrl.SetRowHeight(0,24);
for (int col = 0; col < m_pGridCtrl.GetColumnCount(); col++)
{
GV_ITEM Item;
Item.mask = GVIF_TEXT|GVIF_FORMAT;
Item.nFormat = DT_CENTER|DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE| DT_END_ELLIPSIS;
Item.row = row;
Item.col = col;
Item.strText = GridColtable[col];
if(row < m_nFixRows )
m_pGridCtrl.SetRowHeight(row,24);
else
m_pGridCtrl.SetRowHeight(row,22);
m_pGridCtrl.SetColumnWidth(col,Gridwidth[col]);
m_pGridCtrl.SetItem(&Item);
}
for (int col = 1; col < m_pGridCtrl.GetRowCount(); col++)
{
Item.row = col;
Item.col = row;
Item.strText.Format(_T("%d"),col);
m_pGridCtrl.SetItem(&Item);
m_pGridCtrl.SetRowHeight(col,24);
}
for (int row = 1; row < m_pGridCtrl.GetRowCount(); row++)
{
for (int col = 1; col < m_pGridCtrl.GetColumnCount(); col++)
{
GV_ITEM Item;
Item.mask = GVIF_TEXT|GVIF_FORMAT;
Item.nFormat = DT_CENTER|DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE| DT_END_ELLIPSIS;
Item.row = row;
Item.col = col;
Item.strText = GridColtable[col];
m_pGridCtrl.SetColumnWidth(col,Gridwidth[col]);
m_pGridCtrl.SetItem(&Item);
if (row==1 && col==1)
{
//m_pGridCtrl.SetTextBkColor(RGB(0, 255, 0));
//m_pGridCtrl.SetItemBkColour(row, col, RGB(0, 255, 0));
m_pGridCtrl.SetItemFgColour(row, col, RGB(255, 0, 0));
/*m_pGridCtrl.SetTextColor(RGB(0, 0, 255));
m_pGridCtrl.SetFixedTextColor(RGB(255, 0, 0));
m_pGridCtrl.SetGridLineColor(RGB(255, 0, 255));
m_pGridCtrl.SetGridBkColor(RGB(255, 0, 255));*/
}
}
}
//m_pGridCtrl.SetBkColor(RGB(255, 255, 0));
}
6、 CGridCtrlExampleDlg::OnInitDialog()中調用OnInitialGrid()
OnInitialGrid();
7、在對話框資源中添加CustomContrl控件
8、調整CustomContrl控件屬性,注意Class屬性必須設定為MFCGridCtrl
9、将控件關聯到m_pGridCtrl對象
DDX_GridControl(pDX, IDC_MY_GRIDCTRL, m_pGridCtrl);
10、效果預覽
11、程式源檔案連結:http://pan.baidu.com/s/1mgnBgA8 密碼:a8kd