|
Tech Note 10: The SDIGrid ControlApril 08, 2010© NS BASIC Corporation. All rights reserved. |
The SDIGrid control is part of the CodeGuru project. It is a version, improved by Michael Lombardi, of the MFCGridCtrl. To see a sample program using this control, look at SDIGrid in the Sample folder, contributed by Robert Slack. The actual control, SDIGrid.ocx, is installed with NS Basic/Desktop.
The following is shared from the original article by Chris Maunder at the CodeProject site. We reproduce it here for convenience. Please note that the links in the article are relative to its position in the CodeProject website. If you link back to the orginal article, most work properly. The documentation is for the full control as implemented by Chris Maunder. The actual control that is usable from NS Basic/Desktop is the ActiveX version of the control, which is a subset of the full control, so not all functions and methods described below are available.
After pushing the CListCtrl to its limits in trying to display and edit tabulated data I decided what was really needed was a dedicated grid control. I started writing my own grid control from scratch but decided to save time by modifying Joe Willcoxson's free WorldCom grid control. I tore apert his code and rebuilt it from the ground up in order to get it to do all the things I needed. The code has gone through so many modifications that I'm not sure if there is even a single original line of code. In any case Joe's code was a great framework on which to build.
The project started out as a simple clean up but very quickly ballooned
into a bit of a nightmare as I kept finding new features that I felt just
had to go into it. It has not been tested exhaustively - but I'm
fairly confident that it won't fall over too badly :). Joe was kind enough
to allow me to release the source with no strings attached (since it is
based on his code) but since the project was such a marathon I am placing
a couple of very minor conditions on the use of this code:
This file may be redistributed unmodified by any means PROVIDING
it is not sold for profit without the authors written consent, and providing
that this notice and the authors name and all copyright notices remains
intact. This code may be used in compiled form in any way you desire with
the following conditions. If the source code in this file is used in any
commercial application then a statement along the lines of "Portions copyright
(c) Chris Maunder, 1998-1999" must be included in the startup banner, "About"
box or printed documentation. The source code may not be compiled into
a standalone library and sold for profit. Besides - it's free to whoever
wants it anyway! This software is provided "as is" without express or implied warranty. Use it at your own risk! Whilst I have made every effort to remove any undesirable "features", I cannot be held responsible if it causes any damage or loss of time or data. |
The control features:
To use the Grid control in your project you will need to add a number of
files to your project:
gridctrl.cpp, gridctrl.h | Main grid control source and header files. | |
CellRange.h | Definition of CCellID and CCellRange helper classes. | |
MemDC.h | Keith Rule's memory DC helper class. | |
InPlaceEdit.cpp, InPlaceEdit.h | In-place edit windows source and header files. | |
GridDropTarget.cpp, GridDropTarget.h | Grid control OLE drag and drop target. Only necessary if you don't define GRIDCONTROL_NO_DRAGDROP in gridctrl.h | |
Titletip.cpp, Titletip.h | Titletips for cells, from www.codeguru.com Only necessary if you don't define GRIDCONTROL_NO_TITLETIPS in gridctrl.h |
The underlying class of the grid control is CGridCtrl which is derived from CWnd. To use it, either use the MS Visual C++ dialog editor to place a custom control on a dialog, and enter "MFCGridCtrl" (no quotes) as the Class name, or use CGridCtrl::Create:
CGridCtrl(int nRows = 0, int nCols = 0, int nFixedRows = 0, int nFixedCols = 0); BOOL Create(const RECT& rect, CWnd* parent, UINT nID, DWORD dwStyle = WS_CHILD | WS_BORDER | WS_TABSTOP | WS_VISIBLE); void AFXAPI DDX_GridControl(CDataExchange* pDX, int nIDC, CGridCtrl&rControl);
DDX_GridControl is used where a DDX_Control call is needed. It is necessary to use DDX_GridControl instead of DDX_Control when creating the control via a dialog template in order to ensure that the grid is correctly registered as a drag and drop target. This is to avoid a strange COleDropTarget::Register error that occurs in win95.
int GetRowCount() const |
Returns the number of rows (including fixed rows) |
int GetColumnCount() const |
Returns the number of columns (including fixed columns) |
int GetFixedRowCount() const |
Returns the number of fixed rows |
int GetFixedColumnCount() const |
Returns the number of fixed columns |
BOOL SetRowCount(int nRows)
|
Sets the number of rows (including fixed rows), Returning TRUE on success. |
BOOL SetColumnCount(int nCols)
|
Sets the number of columns (including fixed columns), Returning TRUE on success. |
BOOL SetFixedRowCount(int nFixedRows = 1)
|
Sets the number of fixed rows, returning TRUE on success. |
BOOL SetFixedColumnCount(int nFixedCols = 1)
| Sets the number of columns, returning TRUE on success. |
int GetRowHeight(int nRow) const | Gets the height of row nRow. |
BOOL SetRowHeight(int row, int height) | Sets the height of row nRow. |
int GetColumnWidth(int nCol) const | Gets the width of column nCol |
BOOL SetColumnWidth(int col, int width) | Sets the width of column nCol. |
int GetFixedRowHeight() const | Gets the combined height of the fixed rows. |
int GetFixedColumnWidth() const | Gets the combined width of the fixed columns. |
long GetVirtualHeight() const | Gets the combined height of all the rows. |
long GetVirtualWidth() const | Gets the combined width of all the columns. |
BOOL GetCellOrigin(int nRow, int nCol, LPPOINT p) | Gets the topleft point for cell (nRow,nCol), returning TRUE if successful. (cell must be visible for success). |
BOOL GetCellOrigin(const CCellID& cell, LPPOINT p) | Gets the topleft point for the given cell, returning TRUE if successful. (cell must be visible for success). See also CCellID. |
BOOL GetCellRect(int nRow, int nCol, LPRECT pRect) | Gets the bounding rectangle for the given cell, returning TRUE if successful. (cell must be visible for success). |
BOOL GetCellRect(const CCellID& cell, LPRECT pRect)
| Gets the bounding rectangle for the given cell, returning TRUE if successful. (cell must be visible for success). See also CCellID. |
BOOL GetTextRect(int nRow, int nCol, LPRECT pRect)t | Gets the bounding rectangle for the text in the given cell, returning TRUE if successful. (cell must be visible for success). |
BOOL GetTextRect(const CCellID& cell, LPRECT pRect)
| Gets the bounding rectangle for the text in the given cell, returning TRUE if successful. (cell must be visible for success). See also CCellID. |
void SetImageList(CImageList* pList)
| Sets the current image list for the grid. The control only takes a copy of the pointer to the image list, not a copy of the list itself. |
CImageList* GetImageList() | Gets the current image list for the grid. |
void SetGridLines(int nWhichLines = GVL_BOTH) | Sets which (if any) gridlines are displayed. See here for possible values. |
int GetGridLines()
| Gets which (if any) gridlines are displayed. See here for possible return values. |
void SetEditable(BOOL bEditable = TRUE)
| Sets if the geid is editable. |
BOOL IsEditable() | Gets whether or not the grid is editable. |
void SetModified(BOOL bModified = TRUE, int nRow = -1, int nCol = -1) | Sets the modified flag for a cell. If no row or columns is specified, then change affects the entire grid. |
BOOL GetModified(int nRow = -1, int nCol = -1) | Sets the modified flag for a cell, or if no cell, it returns the status for the entire grid. |
void SetListMode(BOOL bEnableListMode = TRUE)
| Sets the grid into (or out of) List mode. When the grid is in list mode, full row selection is enabled and clicking on the column header will sort the grid by rows. |
BOOL GetListMode() | Get whether or not the grid is in list mode. |
void SetSingleRowSelection(BOOL bSing = TRUE)
| Sets the grid into (or out of) Single row selection mode. This mode is only effective when in ListMode. When in this mode, only a single row at a time can be selected, so the grid behaves somewhat like a multicolumn listbox. |
BOOL GetSingleRowSelection() | Get whether or not the grid is in single row selection mode. |
void EnableSelection(BOOL bEnable = TRUE)
| Sets whether or not the grid cells can be selected. |
BOOL IsSelectable() | Get whether or not grid cells are selectable. |
void EnableDragAndDrop(BOOL bAllow = TRUE)
| Sets whether drag and drop is enabled. |
BOOL GetDragAndDrop() | Get whether drag and drop is allowed. |
void SetRowResize(BOOL bResize = TRUE)
| Sets whether or not rows can be resized. |
BOOL GetRowResize() | Gets whether or not rows can be resized. |
void SetColumnResize(BOOL bResize = TRUE)
| Sets whether or not columns can be resized. |
BOOL GetColumnResize() | Gets whether or not columns can be resized. |
void SetHeaderSort(BOOL bSortOnClick = TRUE)
| Sets whether or not rows are sorted on column header clicks in ListMode. |
BOOL GetHeaderSort() | Gets whether or not rows are sorted on column header clicks in ListMode. |
void SetHandleTabKey(BOOL bHandleTab = TRUE)
| Sets whether or not the TAB key is used to move the cell selection. |
BOOL GetHandleTabKey() | Gets whether or not the TAB key is used to move the cell selection. |
void SetDoubleBuffering(BOOL bBuffer = TRUE)
| Sets whether or not double buffering is used when painting (avoids flicker). |
BOOL GetDoubleBuffering() | Gets whether or not double buffering is used when painting. |
void EnsureVisible(CCellID &cell)
| Ensures that the specified cell is visible. |
BOOL IsCellVisible(CCellID &cell) const | Returns TRUE if the cell is visible. |
BOOL IsCellEditable(CCellID &cell) const | Returns TRUE if the cell is editable. |
void EnsureVisible(int nRow, int nCol) | Ensures that the specified cell is visible. |
void EnableTitleTips(BOOL bEnable = TRUE)
| Sets whether or not titletips are used. |
BOOL GetTitleTips() | Gets whether or not titletips are used. |
BOOL IsCellFixed(int nRow, int nCol) | Returns TRUE if the given cell is a fixed cell. |
void SetTextColor(COLORREF clr)
| Sets the colour of the text in non-fixed cells. |
COLORREF GetTextColor() | Gets the colour of the text in non-fixed cells. |
void SetTextBkColor(COLORREF clr)
| Sets the background colour of the non-fixed cells. |
COLORREF GetTextBkColor() | Gets the background colour of the non-fixed cells. |
void SetFixedTextColor(COLORREF clr)
| Sets the colour of the text in fixed cells. |
COLORREF GetFixedTextColor() | Gets the colour of the text in fixed cells. |
void SetFixedBkColor(COLORREF clr)
| Sets the background colour of the fixed cells. |
COLORREF GetFixedBkColor() | Gets the background colour of the fixed cells. |
void SetBkColor(COLORREF clr)
| Sets the background colour of the control (the area outside fixed and non-fixed cells). |
COLORREF GetBkColor() | Gets the background colour of the control. |
void SetGridColor(COLORREF clr)
| Sets the colour of the gridlines. |
COLORREF GetGridColor() | Gets the colour of the grid lines. |
See also the Individual Cell colour functions that allow an individual cell's colours to be changes seperate to the rest of the grid.
int GetSelectedCount()
| Gets the number of selected cells. |
CCellID GetFocusCell() | Gets the cell with the focus. See also CCellID. |
BOOL SetItem(const GV_ITEM* pItem)
| Sets the contents of a cell with the values from the GV_ITEM structure. Note that the value of the mask field will determine which values are actually changed (cf. CListCtrl::SetItem). |
BOOL GetItem(GV_ITEM* pItem) | Fills the GV_ITEM structure with values from the specified cell. Note that the value of the mask field will determine which values are actually retrieved (cf. CListCtrl::GetItem). |
BOOL SetItemText(int nRow, int nCol, LPCTSTR str) | Sets the text for the given cell. Returns TRUE on success |
virtual CString GetItemText(int nRow, int nCol) | Gets the text for the given cell. This function is virtual in order to aid extensibility. No more messing around with LVN_GETDISPINFO messages or string pooling! |
BOOL SetItemData(int nRow, int nCol, LPARAM lParam) | Sets the lParam (user-defined data) field for the given cell. Returns TRUE on success. See also GV_ITEM. |
LPARAM GetItemData(int nRow, int nCol) const | Gets the lParam (user-defined data) field for the given cell. See also GV_ITEM. |
BOOL SetItemImage(int nRow, int nCol, int iImage) | Sets the image index for the given cell. Returns TRUE on success. See also GV_ITEM. |
int GetItemImage(int nRow, int nCol) const | Gets the image index for the given cell. |
BOOL SetItemState(int nRow, int nCol, UINT state) | Sets the state of the given cell. Returns TRUE on success. See also GV_ITEM. |
UINT GetItemState(int nRow, int nCol) const | Gets the state of the given cell. See also GV_ITEM. |
BOOL SetItemFormat(int nRow, int nCol, UINT nFormat) | Sets the format of the given cell. Returns TRUE on success. Default implementation of cell drawing uses CDC::DrawText, so any of the DT_* formats are available. See also GV_ITEM. |
UINT GetItemFormat(int nRow, int nCol) const | Gets the format of the given cell (default returns a CDC::DrawText DT_* format). See also GV_ITEM. |
BOOL SetItemBkColour(int nRow, int nCol, COLORREF cr = CLR_DEFAULT) | Sets the background colour of the given cell. Returns TRUE on success. See also GV_ITEM. |
COLORREF GetItemBkColour(int nRow, int nCol) const | Gets the background colour of the given cell. See also GV_ITEM. |
BOOL SetItemFgColour(int nRow, int nCol, COLORREF cr = CLR_DEFAULT) | Sets the foreground colour of the given cell. Returns TRUE on success. See also GV_ITEM. |
COLORREF GetItemFgColour(int nRow, int nCol) const | Gets the foreground colour of the given cell. See also GV_ITEM. |
BOOL SetItemFont(int nRow, int nCol, LOGFONT* lf) | Sets the font of the given cell. Returns TRUE on success. See also GV_ITEM. |
LOGFONT* GetItemFont(int nRow, int nCol) const | Gets the font of the given cell. See also GV_ITEM. |
int InsertColumn(LPCTSTR strHeading, UINT nFormat, int nColumn = -1) | Inserts a column at the position given by nCol, or at the end of all columns if nCol is < 0. strHeading is the column heading and nFormat the format. Returns the position of the inserted column. |
int InsertRow(LPCTSTR strHeading, int nRow = -1) | Inserts a row at the position given by nRow, or at the end of all rows if nRow is < 0. strHeading is the row heading. The format of each cell in the row will be that of the cell in the first row of the same column. Returns the position of the inserted row. |
BOOL DeleteColumn(int nColumn)
| Deletes column "nColumn", return TRUE on success. |
BOOL DeleteRow(int nRow)
| Deletes row "nRow", return TRUE on success. |
BOOL DeleteAllItems() | Deletes all rows and contents in the grid. |
BOOL DeleteNonFixedRows() | Deletes all non-fixed rows in the grid. |
BOOL AutoSizeRow(int nRow)
| Auto sizes the row to the size of the largest item. |
BOOL AutoSizeColumn(int nCol)
| Auto sizes the column to the size of the largest item. |
void AutoSizeRows()
| Auto sizes all rows. |
void AutoSizeColumns()
| Auto sizes all columns. |
void AutoSize()
| Auto sizes all rows and columns. |
void ExpandColumnsToFit()
| Expands the column widths to fit the grid area. |
void ExpandRowsToFit()
| Expands the row heights to fit the grid area. |
void ExpandToFit()
| Expands the rows and columns to fit the grid area. |
CSize GetTextExtent(LPCTSTR str, BOOL bUseSelectedFont = TRUE) | Gets the extent of the text pointed to by str. By default this uses the selected font (which is a bigger font). |
void SetRedraw(BOOL bAllowDraw,
BOOL bResetScrollBars = FALSE)
| Stops/starts redraws on things like changing the number of rows and columns and autosizing, but not for user-intervention such as resizes. |
BOOL RedrawCell(int nRow, int nCol, CDC* pDC = NULL) | Redraws the given cell. Drawing will be via the pDC if one is supplied. |
BOOL RedrawCell(const CCellID& cell, CDC* pDC = NULL) | Redraws the given cell. Drawing will be via the pDC if one is supplied. |
BOOL RedrawRow(int row)
| Redraws the given row. |
BOOL RedrawColumn(int col)
| Redraws the given column. |
CCellRange GetCellRange() | Gets the range of cells for the entire grid. See also CCellRange. |
void SetSelectedRange(const CCellRange& Range, BOOL bForceRepaint = FALSE); | Sets the range of selected cells. See also CCellRange. |
void SetSelectedRange(int nMinRow, int nMinCol, int nMaxRow, int nMaxCol, BOOL bForceRepaint = FALSE); | Sets the range of selected cells. |
BOOL IsValid(int nRow, int nCol) | Returns TRUE if the given row and column is valid. |
BOOL IsValid(const CCellID& cell)
| Returns TRUE if the given cell is valid. |
BOOL IsValid(const CCellRange& range)
| Returns TRUE if the given cell range is valid. |
CCellID GetNextItem(CCellID& cell, int nFlags) const | Searches for a cell that has the specified properties and that bears the specified relationship to a given item. (See also CListCtrl::GetNextItem and Cell Searching options) |
BOOL SortTextItems(int nCol, BOOL bAscending)
| Sorts the grid on the given column based on cell text. Returns TRUE on success. |
BOOL SortItems(PFNLVCOMPARE pfnCompare, int nCol,
BOOL bAscending, LPARAM data = 0)
| Sorts the grid on the given column using the supplied compare function pfnCompare. See CListCtrl::SortItems for information in the form of this function. Returns TRUE on success. |
void Print()
| Prints the grid control on the user selected device. (Useful where the control is used in a dialog) |
virtual void OnBeginPrinting(CDC *pDC, CPrintInfo *pInfo) | Used in a Doc/View environment. Call in your CView dervied class' OnBeginPrinting. |
virtual void OnPrint(CDC *pDC, CPrintInfo *pInfo) | Used in a Doc/View environment. Call in your CView dervied class' OnPrint. |
virtual void OnEndPrinting(CDC *pDC, CPrintInfo *pInfo) | Used in a Doc/View environment. Call in your CView dervied class' OnEndPrinting. |
The CCellID class. This is a handy helper class used
to reference individual cells. All members are public. This class is
adapted from Joe Willcoxsons original implementation.
The CCellRange class. This is a handy helper class used
to reference cell ranges. This class is adapted from Joe Willcoxsons original
implementation.
The GV_ITEM structure. This structure is used for Get/SetItem calls.
class CCellID
{
public:
int row, col; // The zero based row and column of the cell.
CCellID(int nRow = -1, int nCol = -1)
int IsValid();
int operator==(const CCellID& rhs);
int operator!=(const CCellID& rhs);
}
class CCellRange
{
public:
CCellRange(int nMinRow = -1, int nMinCol = -1, int nMaxRow = -1, int nMaxCol = -1);
void Set(int nMinRow = -1, int nMinCol = -1, int nMaxRow = -1, int nMaxCol = -1);
int IsValid() const;
int InRange(int row, int col) const; // Is the row/col in the range?
int InRange(const CCellID& cellID) const; // is the cell in the range?
CCellID GetTopLeft() const; // Get topleft cell in range
CCellRange Intersect(const CCellRange& rhs) const;
// Returns the intersection of
// two cell ranges
int GetMinRow() const; // Self explanatory
void SetMinRow(int minRow);
int GetMinCol() const;
void SetMinCol(int minCol);
int GetMaxRow() const;
void SetMaxRow(int maxRow);
int GetMaxCol() const;
void SetMaxCol(int maxCol);
int GetRowSpan() const; // Number of rows spanned
int GetColSpan() const; // Number of columns spanned
int operator==(const CCellRange& rhs);
int operator!=(const CCellRange& rhs);
}
typedef struct _GV_ITEM {
int row,col; // Row and Column of item
UINT mask; // Mask for use in getting/setting cell data
UINT state; // cell state (focus/hilighted etc)
UINT nFormat; // Format of cell. Default imaplentation used CDC::DrawText formats
CString szText; // Text in cell
int iImage; // index of the list view items icon
COLORREF crBkClr; // Background colour (or CLR_DEFAULT)
COLORREF crFgClr; // Forground colour (or CLR_DEFAULT)
LPARAM lParam; // 32-bit value to associate with item
LOGFONT lfFont; // cell font
} GV_ITEM;
Grid line selection
GVL_NONE - No grid lines
GVL_HORZ - Horizontal lines only
GVL_VERT - Vertical lines only
GVL_BOTH - Both vertical and horizontal lines
Cell data mask
GVIF_TEXT - Cell text will be accessed
GVIF_IMAGE - Cell image number will be accessed
GVIF_PARAM - Cell user data (lParam) will be accessed
GVIF_STATE - Cell state will be accessed
GVIF_BKCLR - Cell background colour will be accessed
GVIF_FGCLR - Cell foreground colour will be accessed
GVIF_FORMAT - Cell format field will be accessed
GVIF_FONT - Cell logical font will be accessed
Cell states
GVIS_FOCUSED - Cell has focus GVIS_SELECTED - Cell is selected GVIS_DROPHILITED - Cell is drop highlighted GVIS_READONLY - Cell is read-only and cannot be edited GVIS_FIXED - Cell is fixed (not used) GVIS_MODIFIED - Cell has been modifiedCell Searching options
GVNI_FOCUSED - Search for focus cell GVNI_SELECTED - Search for selected cells GVNI_DROPHILITED - Search for drop highlighted cells GVNI_READONLY - Search for read-only cells GVNI_FIXED - Search for fixed cells (not used) GVNI_MODIFIED - Search for modified cells GVNI_ABOVE - Search above initial cell GVNI_BELOW - Search below initial cell GVNI_TOLEFT - Search to the left of the initial cell GVNI_TORIGHT - Search to the right of the initial cell GVNI_ALL - Search all cells in the grid starting from the given cell GVNI_AREA - Search all cells below and to the right of the given cellNotification messages
GVN_BEGINDRAG - Sent when dragging starts GVN_BEGINLABELEDIT - Sent when inplace editing starts GVN_ENDLABELEDIT - Sent when inplace editing stops
These messages are exactly the same as their LVN_... counterparts, except they use an NM_GRIDVIEW structure:
typedef struct tagNM_GRIDVIEW { NMHDR hdr; int iRow; int iColumn; } NM_GRIDVIEW;
These functions have been made virtual to aid extensiblity.
Printing - called in OnPrint.
virtual void PrintColumnHeadings(CDC *pDC, CPrintInfo *pInfo); virtual void PrintHeader(CDC *pDC, CPrintInfo *pInfo); virtual void PrintFooter(CDC *pDC, CPrintInfo *pInfo);
Drag n' drop
virtual CImageList* CreateDragImage(CPoint *pHotSpot) - No longer necessary but I
thought the code was cool so
kept it :).
Mouse Clicks
virtual void OnFixedColumnClick(CCellID& cell); virtual void OnFixedRowClick(CCellID& cell);
Editing
virtual void OnEditCell(int nRow, int nCol, UINT nChar) - Starting edit virtual void OnEndEditCell(int nRow, int nCol, CString str) - ending edit virtual void CreateInPlaceEditControl(CRect& rect, DWORD dwStyle, int nRow, int nCol, LPCTSTR szText, int nChar) - Create the inplace edit control
Drawing
virtual CSize GetCellExtent(int nRow, int nCol, CDC* pDC) - Returns Size of cell according to cell contents. virtual void OnDraw(CDC& origDC); - Draws everything virtual BOOL DrawFixedCell(CDC* pDC, int nRow, int nCol, - Draws Fixed cells CRect rect, BOOL bEraseBk=FALSE) virtual BOOL DrawCell(CDC* pDC, int nRow, int nCol, - Draws normal cells CRect rect, BOOL bEraseBk=FALSE)
Construction and Cleanup
virtual CGridCell* CreateCell(int nRow, int nCol) - Creates a new cell and initialises it. virtual void EmptyCell(CGridCell* cell, int nRow, int nCol) - Performs any cleanup necessary before removing cells
A number of Clipboard functions have been included.
virtual void OnEditCut() | Copies contents of selected cells to clipboard and deletes the contents of the selected cells. (Ctrl-X) |
virtual void OnEditCopy() | Copies contents of selected cells to clipboard. (Ctrl-C) |
virtual void OnEditPaste() | Pastes the contents of the clipboard to the grid. (Ctrl-V) |
virtual void OnEditSelectAll() | Not actually a clipboard function, but handy nevertheless. This routine selects all cells in the grid. (Ctrl-A) |
This would not have been possible without the following authors making their code freely available:
Version
Last updated: April 10, 1999.