Click here to Skip to main content
15,861,168 members
Articles / Desktop Programming / MFC

Using comboboxes in the MFC Grid Control

Rate me:
Please Sign up or sign in to vote.
4.91/5 (47 votes)
8 Jan 2013CPOL 452.2K   8.2K   122   115
Explains how to use comboboxes to edit cells in the MFC Grid Control

Sample Image - gridctrl_combo.gif

Introduction

Since I posted my MFC grid control I've had a lot of requests asking how to use other methods of editing cells in the grid. Ken Bertelson has taken this to the extreme, with his Grid Tree control. For some this was a little too involved, so I've created a demo project that shows how to replace the default editing with a simple combo box.

Previous methods of achieving this required that a new CGridCtrl derived class be created. With the new structure in the 2.X versions of CGridCtrl it's now a lot simpler.

A new cell type

Changing the way cells are edited is simply a matter of deriving a new grid cell class from CGridCellBase (or derivatives such as CGridCell).

I'm using the In-Place list that I used in previous versions. It's not the greatest - but it does demonstrate how to replace the default editing.

The first step is to derive a new class from CGridCell - I call it CGridCellCombo - and override Edit (which initiates editing) and EndEdit (which stops editing). You can find this class in the GridCellCombo.* files.

In Edit I create a CWnd derived class that will perform the actual editing - in this case my CInPlaceList from previous versions of the grid. There are a number of things to be aware of when creating such CWnd derived Edit classes:

  • The control will receive the row and column to be edited, the dimensions and location of the in-place edit control, the style of control to create, the original text in the cell plus the initial character that caused editing to commence (or VK_LBUTTON if the mouse was clicked on the current cell).
  • Your editing control should stop editing when it loses input focus.
  • Your editing object should handle mouse keys in a way that allows the user to navigate between cells while editing. If the control gets an arrow key for instance, it should cancel editing and return the last key it encountered back to the grid via the GVN_ENDLABELEDIT notification message.
    Note that the grid control accepts Ctrl+<arrows> for navigation, so if your in-place edit control needs to use the arrows, you can always reserve Ctrl+<arrows> to move to other cells.
  • Your edit control should pass back information about the last key pressed before editing ended. This allows correct movement among cells

The EndEdit function of your grid cell class should cease editing and destroy the in-place editing window.

If you look at the code you will see that the grid cell derived class is merely a wrapper that creates an instance of a CInPlaceList window and then sits back with the knowledge of a job well done. The actual guts of the grid cell class are as follows:

C++
// Create a control to do the editing
BOOL CGridCellCombo::Edit(int nRow, int nCol, CRect rect, CPoint /* point */,
                          UINT nID, UINT nChar)
{
    m_bEditing = TRUE;
    
    // CInPlaceList auto-deletes itself
    m_pEditWnd = new CInPlaceList(GetGrid(), rect, GetStyle(), nID, nRow, nCol, 
                                  m_Strings, GetText(), nChar);

    return TRUE;
}

// Cancel the editing.
void CGridCellCombo::EndEdit()
{
    if (m_pEditWnd)
        ((CInPlaceList*)m_pEditWnd)->EndEdit();
}

We rely on CGridCell::OnEndEdit to set m_bEditing to FALSE and m_pEditWnd to NULL when editing has finished. CInPlaceList is also self-deleting, which saves a whole line of code in EndEdit.

The CInPlaceList does the actual work, and keeps track of issues such as the last key pressed and it's current focus state. It also has niceties such as ensuring that the drop down list is correctly sized.

The major issue is that the control must pass the necessary data back to the parent grid once editing has been completed. It uses the following code snippet in it's EndEdit method to do this:

C++
void CInPlaceList::EndEdit()
{
    CString str;
    GetWindowText(str);
 
    // Send Notification to parent
    GV_DISPINFO dispinfo;

    dispinfo.hdr.hwndFrom = GetSafeHwnd();
    dispinfo.hdr.idFrom   = GetDlgCtrlID();
    dispinfo.hdr.code     = GVN_ENDLABELEDIT;
 
    dispinfo.item.mask    = LVIF_TEXT|LVIF_PARAM;
    dispinfo.item.row     = m_nRow;
    dispinfo.item.col     = m_nCol;
    dispinfo.item.strText = str;
    dispinfo.item.lParam  = (LPARAM) m_nLastChar; 
 
    CWnd* pOwner = GetOwner();
    if (IsWindow(pOwner->GetSafeHwnd()))
        pOwner->SendMessage(WM_NOTIFY, GetDlgCtrlID(), (LPARAM)&dispinfo );
 
    // Close this window (PostNcDestroy will delete this)
    PostMessage(WM_CLOSE, 0, 0);
}

I pass the character that initiated editing to the edit control itself so that it can deal with keys appropriately. For instance in the default edit control, if the edit control is passed a normal character or arrow key as the "initiating" key, then it will cease editing when it encounters an arrow key (to allow navigation using the keyboard). If the edit control is passed VK_LBUTTON (meaning editing was initiated by a mouse click) then arrow keys will not cause the editing to cease.

One last thing I do is ensure that the new cell displays a user hint that it is not a normal grid cell. When a cell is selected I override drawing so that a small drop down arrow is shown. The code is quite simple:

C++
BOOL CGridCellCombo::Draw(CDC* pDC, int nRow, int nCol, CRect rect,
                          BOOL bEraseBkgnd /*=TRUE*/)
{
    // Cell selected?
    DWORD dwState = GetState();
    if ( !(dwState & GVIS_FIXED) && (dwState & GVIS_FOCUSED))
    {
        // Get the size of the scroll box
        CSize sizeScroll(GetSystemMetrics(SM_CXVSCROLL), 
                         GetSystemMetrics(SM_CYHSCROLL));

        // enough room to draw?
        if (sizeScroll.cy < rect.Width() && sizeScroll.cy < rect.Height())
        {
            // Draw control at RHS of cell
            CRect ScrollRect = rect;
            ScrollRect.left   = rect.right - sizeScroll.cx;
            ScrollRect.bottom = rect.top + sizeScroll.cy;

            // Do the draw 
            pDC->DrawFrameControl(ScrollRect, DFC_SCROLL, DFCS_SCROLLDOWN);

            // Adjust the remaining space in the cell
            rect.right = ScrollRect.left;
        }
    }

    // drop through and complete the cell drawing using the base class' method
    return CGridCell::Draw(pDC, nRow, nCol, rect,  bEraseBkgnd);
}

Using the new cell type

Using the new cell is simple. You can either use the Grid control's default cell instantiation method (ie. do nothing) and then call CGridCtrl::SetCellType or you can call CGridCtrl::SetDefaultCellType and then do nothing. The first option changes cells from one type to another, and is good if you only want specific cells to be affected. The second option tells the grid the class type that you want to be used at the outset, and is good if you want all cells in the grid to be of your new type.

Thanks

Thanks go to Roelf Werkman for his work in extending the CInPlaceList to allow the CBS_DROPDOWN and CBS_SIMPLE styles to be used, and thanks to Fred Ackers for moticating me to finally write this up.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
QuestionHow can we use search comboboxes in MFC Grid Control Pin
Member 110189751-Sep-14 7:54
Member 110189751-Sep-14 7:54 
GeneralLots of Flickering Pin
Mohd Amanullah Zafar5-May-11 19:18
Mohd Amanullah Zafar5-May-11 19:18 
GeneralAncient article - needs .asp moved to .aspx Pin
Iain Clarke, Warrior Programmer10-Nov-10 3:11
Iain Clarke, Warrior Programmer10-Nov-10 3:11 
GeneralRe: Ancient article - needs .asp moved to .aspx Pin
Sean Ewington10-Nov-10 11:01
staffSean Ewington10-Nov-10 11:01 
QuestionQuestion for License... Pin
BK CHA7-Sep-08 16:45
BK CHA7-Sep-08 16:45 
AnswerRe: Question for License... Pin
Chris Maunder30-Sep-08 11:02
cofounderChris Maunder30-Sep-08 11:02 
QuestionHow to Center-Align Combobox Items During Dropdown? Pin
demxine3-Sep-08 22:40
demxine3-Sep-08 22:40 
GeneralCut & Copy in DLL's Pin
stevetex1-Jun-07 3:34
stevetex1-Jun-07 3:34 
GeneralRe: Cut & Copy in DLL's Pin
tmpuserz30-Mar-11 10:54
tmpuserz30-Mar-11 10:54 
GeneralRe: Cut & Copy in DLL's Pin
tmpuserz30-Mar-11 11:14
tmpuserz30-Mar-11 11:14 
QuestionHow to generate a CBN_SELCHANGE or CBN_CLOSEUP message Pin
tlillys24-Apr-07 12:24
tlillys24-Apr-07 12:24 
AnswerRe: How to generate a CBN_SELCHANGE or CBN_CLOSEUP message Pin
tlillys27-Apr-07 15:01
tlillys27-Apr-07 15:01 
Question"Number" combo Pin
andrewtruckle22-Feb-07 20:42
andrewtruckle22-Feb-07 20:42 
QuestionBeep when I hit ENTER Pin
andrewtruckle5-Feb-07 0:51
andrewtruckle5-Feb-07 0:51 
AnswerRe: Beep when I hit ENTER Pin
andrewtruckle9-Feb-07 10:29
andrewtruckle9-Feb-07 10:29 
QuestionDisabling the cell Pin
andrewtruckle23-Jan-07 0:45
andrewtruckle23-Jan-07 0:45 
AnswerRe: Disabling the cell Pin
andrewtruckle23-Jan-07 0:51
andrewtruckle23-Jan-07 0:51 
I sorted it out:

// Do the draw <br />
 // AJT FIX for disabled cell<br />
 if (GetGrid()->IsWindowEnabled())<br />
     pDC->DrawFrameControl(ScrollRect, DFC_SCROLL, DFCS_SCROLLDOWN );<br />
 else<br />
     pDC->DrawFrameControl(ScrollRect, DFC_SCROLL, DFCS_SCROLLDOWN|DFCS_INACTIVE );

QuestionItem Index Pin
andrewtruckle17-Jan-07 8:46
andrewtruckle17-Jan-07 8:46 
AnswerRe: Item Index Pin
Andrew Truckle22-Jan-17 5:34
Andrew Truckle22-Jan-17 5:34 
AnswerRe: Item Index Pin
Andrew Truckle24-Jan-17 10:42
Andrew Truckle24-Jan-17 10:42 
Questionhow to have a combo in the header? Pin
Arris7413-Jan-07 23:16
Arris7413-Jan-07 23:16 
QuestionCGridCellCombo and itemData. Pin
lollinus17-Oct-06 3:04
lollinus17-Oct-06 3:04 
AnswerRe: CGridCellCombo and itemData. Pin
lollinus17-Oct-06 4:30
lollinus17-Oct-06 4:30 
QuestionHow a can display the list of the combo-box Pin
xkill27-Aug-06 8:57
xkill27-Aug-06 8:57 
GeneralEditing Cells in MFC Pin
Sarah2Frog7-Jun-06 4:57
Sarah2Frog7-Jun-06 4:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.