Click here to Skip to main content
Click here to Skip to main content

Using the CComboBox control

By , 23 Mar 2001
 

Introduction

This tutorial will show how use the CComboBox class in a very basic dialog based application. It will cover the following points:

  • Adding a CComboBox to your dialog
  • Changing the height of the Dropdown List
  • The difference in behaviour of the 3 styles of CComboBox
  • Inserting/Adding items to the CComboBox
  • Changing the width of the dropdown list
  • Using item data
  • Determining which item is selected
  • Selecting items
  • Handling CComboBox messages
  • Enhancements

A ComboBox is a composite control that consists of an Edit control and a List box control. This tutorial assumes the you are comfortable with creating a dialog based application using the VC++ 6 Class Wizard. If you require information on this topic consult the article A Beginners Guide to Dialog Base Applications - Part 1.

Adding a CComboBox to your dialog

When your dialog-based application is generated, go to the Resources in the Workspace window. Select the dialog IDD_COMBOBOXTUTORIAL_DIALOG in the Dialog section. To insert the ComboBox control, select it from the Control palette. The cross shaped cursor indicates where the centre of the edit control portion of the combobox will be placed.

Changing the height of the Dropdown List

Right click on the ComboBox's 'dropdown' button. This will indicate the present size the combo box, including the extended list box. Then resize it by dragging out the rectangle as you would any other control.

The different in behaviour of the 3 styles of CComboBox

There are three different styles of combo box with different selection properties. To change the style of the combo box Right click on it and select Properties. Then select the Styles tab.

Simple type has a permanently open list box and you are able to type in Edit control.

Dropdown type has a 'closed' list box which can be opened by clicking on the 'drop down' button. The Edit control WILL accept input.

Drop List type has a 'closed' list box which can be opened by clicking on the 'drop down' button. The Edit control will NOT accept any input.

Inserting/Adding items to the CComboBox

It is possible to add items to the combo box at coding time. This is handy for data that will never need to changed. To do this select the Data tab and add the item, one per line. Use Ctrl+Return to go the next line.

It is however more usual and more flexible to load the items into the combo box at run time. This way they can be loaded from resources and be localized or be changed according other user choices.

In the demonstration you will see that Dropdown combo is loaded from string resources, the Drop List initially uses the list that was set up in the Data tab, and the Simple combobox is left empty.

To ensure that the Simple combobox is empty we simply call the CComboBox class ResetContent() function.

	m_Simple.ResetContent();

The Dropdown is loaded from string resources by the following for loop, simply call the AddString() member function of the CComboBox class.

	CString tmp;
	for( int i=0; i<6; i++ )
	{
		tmp.LoadString(IDS_STRING102 + i);
		m_DropDown.AddString(tmp);
	}

If you then click on the Insert Long Text Item check box the string "" will inserted after the 3rd Option in the Drop List combo box.

Firstly the index of the string needs to found, and we simply call the InsertString() member function of the CComboBox class.

		int idx = m_DropList.FindString(0, "3rd Option");
		CString str;
		str.LoadString(IDS_STRING108);
		// we add one because we want it after 
		m_DropList.InsertString(idx+1, str);

The main thing to be careful of when using InsertString() is that index represents the position before it will be inserted. If the index is -1 the insert will at the end of the list. (i.e. the same as AddString())

Changing the width of the dropdown list

It is best to design the dialog so the combo box can be large enough to fully display the longest option. This is not always possible however. In this case it is handy to widen the drop list so that the entire string can be seen while selecting.

The CComboBox class has a function SetDroppedWidth() for this purpose. This function's input parameter is the outside width of the of the drop list in pixels. First you need the Device Context of the combo box. Then check the length of all the strings in pixels to find the longest.

Note we must also allow for the width of the Scroll bar and window border.

		CDC* pDC = m_DropList.GetDC();
		CSize sz;
		int newWidth = 0;
		int nWidth = m_DropList.GetDroppedWidth(); 
		for( int i=0; i < m_DropList.GetCount();  i++ )
		{
		   m_DropList.GetLBText( i, str );
		   sz = pDC->GetTextExtent(str);

		   if(sz.cx > newWidth)
			  newWidth = sz.cx;
		}
		// Add allowance for vertical scroll bar and edges
		newWidth += (GetSystemMetrics(SM_CXVSCROLL) + 2*GetSystemMetrics(SM_CXEDGE));
		nWidth = max(nWidth, newWidth);
		m_DropList.SetDroppedWidth( nWidth );
		m_DropList.ReleaseDC(pDC);

Check if the string is longer than the existing drop list, and don't forget to call ReleaseDC().

Calling m_DropList.GetWindowRect( &rc ); will return the width of the edit box and can therefore be used to return the drop list to it's original size.

When using a simple it best to set the Auto Horizontal scroll Style.

Determining which item is selected

There are two ways to determine which item is selected. You can use Class Wizard to associated a control and data variable with the control.

Also add an OnSelChanged function for the combo box with Class Wizard.

Drop List combo boxes can have an integer data variable which returns the index of the selected item, and the code be as simple as below. UpdateData(); transfers the index to the variable.

	void CComboBoxTutorialDlg::OnDropListSelchange() 
	{
		UpdateData();

		if( m_nDropListIndex < 0 ) return;

		CString str;
		m_DropList.GetLBText( m_nDropListIndex, str );
		CString Out;
		Out.Format( "Drop List Selection => index %d\n%s", m_nDropListIndex, str );
		AfxMessageBox( Out ); 
	}

DropDown and Simple combo boxes can have a CString data variable which returns the selected string. To get the string you can again call UpdateData();, or call GetCurSel().

	void CComboBoxTutorialDlg::OnSimpleSelchange() 
	{
		CString str;
		int idx = m_Simple.GetCurSel();
		if( idx < 0 ) return;

		m_Simple.GetLBText( idx, str );
		CString Out;
		Out.Format( "Drop List Selection => index %d\n%s", idx, str );
		AfxMessageBox( Out ); 
	}

You will notice that Class Wizard will only allow you attach an integer variable to a DropList Combo box and a CString variable to the DropDown and Simple Combo boxes.

You can add the Data Exchange entry to attach the alternate variable type manually, but the entry and the variable declaration must be placed outside the AFX_DATA_MAP and AFX_DATA tags so that Class Wizard won't remove them.

.
.
	int		m_nDropListIndex;
	//}}AFX_DATA
	CString	m_strDropList;
.
.
.
.
	DDX_CBIndex(pDX, IDC_COMBO2, m_nDropListIndex);
	//}}AFX_DATA_MAP
	DDX_CBString(pDX, IDC_COMBO2, m_strDropList);
}

Check the string in CBN_SELCHANGE handler after the call to UpdateData().

Selecting items

Selecting an item can be done by setting the index as below. If you use the integer variable call UpdateData(FALSE);

You can use SetCurSel( index )

OR use SelectString( after, str ) where after is the index after which to start searching. As you can see from the demo the items are added in a different order to which they are displayed and the data remains matched.

		m_nDropListIndex = 2;
		UpdateData(FALSE);
		m_Simple.SetCurSel(2);

		CString str;
		str.LoadString(IDS_STRING104);
		m_DropDown.SelectString(0,str);	

If you know that the index can never be set to one lager than the number of items in the list the code can be left as it is. If there is a risk of this however then it is wise to check and either set the index to a default item or send a message box to the user waring of the error.

		if( m_Simple.GetCount() <= 2 )
		{
			m_Simple.SetCurSel(0);
			AfxMessageBox( "Index is out of range, selecting default" );
		}

Using item data

A combo box returns a zero based index of the selected item or the string as shown above. Often the program actually uses a value other than the string or the index, and what's more you need to get this value correct whether the items in the list are sorted or not. If the application is to support multiple languages this is even more important because sorting can be different.

To assists with this each item in the list can have a DWORD associated with it, and this remains attached to the string regardless of the sorting.

Use SetItemData( idx, dwData ) and GetItemData( idx ). When setting the data use the index returned by the AddString() or InsertString() functions to ensure you get it right.

		int idx = m_DropDown.AddString( str.Left(pos));
		m_DropDown.SetItemData( idx, dw );

To retrieve the data get the item index and call GetItemData(idx)

.
		int idx = m_DropDown.GetCurSel();
.
.
		DWORD dw = m_DropDown.GetItemData( idx );
.

Handling CComboBox messages

The notification messages available for combo boxes are the following

CBN_ERRSPACE notification message is sent when a combo box cannot allocate enough memory.

CBN_SELCHANGE notification message is sent when the user changes the current selection in the list box of a combo box.

CBN_DBLCLK notification message is sent when the user double-clicks a string in the list box of a combo box.

CBN_SETFOCUS notification message is sent when a combo box receives the keyboard focus.

CBN_KILLFOCUS notification message is sent when a combo box loses the keyboard focus.

CBN_EDITCHANGE notification message is sent after the user has taken an action that may have altered the text in the edit control portion of a combo box.

CBN_EDITUPDATE notification message is sent when the edit control portion of a combo box is about to display altered text.

CBN_DROPDOWN notification message is sent when the list box of a combo box is about to be made visible.

CBN_CLOSEUP notification message is sent when the list box of a combo box has been closed.

CBN_SELENDOK notification message is sent when the user selects a list item, or selects an item and then closes the list.

CBN_SELENDCANCEL notification message is sent when the user selects an item, but then selects another control or closes the dialog box.

The demo handles the CBN_SELCHANGE and CBN_EDITUPDATE messages. The CBN_EDITUPDATE is handy if you like to prevent some characters from being typed.

The code below is for demonstration only and this kind of validation is best carried out by the control itself. This would involve subclassing the control and overriding of some functions. This more complex topic is discussed elsewhere on this site.

	void CComboBoxTutorialDlg::OnSimpleEditupdate() 
	{
		UpdateData();
		if(!m_strSimple.GetLength()) return;
		DWORD dwSel =  m_Simple.GetEditSel();
		// Only do this if no characters are selected
		if( LOWORD( dwSel ) != LOWORD( dwSel ) ) return;

		if( ispunct( m_strSimple[LOWORD( dwSel )-1] ))
		{
			MessageBeep(0);
			m_strSimple = m_strSimple.Left(LOWORD( dwSel )-1) + m_strSimple.Mid(LOWORD( dwSel ));
			UpdateData(FALSE);
			// put caret back where it was
			m_Simple.SetEditSel( LOWORD( dwSel ), LOWORD( dwSel ) );
	//		AfxMessageBox( "Punctuation Characters are not permitted." );
		}
	}

A word or two of caution. Validation can also be done in the CBN_KILLFOCUS handler. If you do this take care in the way you change incorrect data back and pop up message boxes that also take focus from the control. The program can finish up in an unfortunate loop of validation and message box display.

Enhancements

Some code you may like to play with, is to vary the number of lines of items displayed in the drop down list. This will prevent empty lines at the end of the list and change the height from what was set in the resource editor. The framework does handle some of these things already but sometimes it good to have the control.

	void CComboBoxTutorialDlg::SetNumberOfLines(int nLines)
	{
		// This limits the maximum number of visible entries to 7
		nLines = min( max(nLines, 1), 7 );  
		CRect lprect;
		m_DropDown.GetWindowRect( &lprect );
		lprect.bottom = lprect.top + nLines * m_DropDown.GetItemHeight( -1 ) + lprect.Height();
		m_DropDown.SetWindowPos(NULL, 0, 0, lprect.Width(), lprect.Height(), SWP_NOMOVE | SWP_NOZORDER );
	}

The ENTER key, by default, is only processed by the combo box when the drop list is open, and in this case it has the same effect as a mouse click and makes the selection. A Simple combo box does not process the ENTER key at all and is passed to the parent dialog. If you wish to handle the ENTER key in any other way the combo box will need to be subclassed and handler written for the purpose. You may like to check out Implementing an autocompleting Combobox - By Chris Maunder as a starting point to which the handler can be added.

Conclusion

The Message handlers in this tutorial are the most commonly used and should indicate that they need not be very complex. More complex issues are handled elsewhere on this site.

Happy programming!

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

About the Author

Wolfram Steinke
Engineer MedTech Global
Australia Australia
Started working with computers when I/O was with punched paper tape, using Algol. Then learned Fortran, Basic, various Assemblers, Forth and Postscript. Built a robot in the early '80s. When I finally got a PC I learned C, C++ and more recently worked on a variety of .NET and PHP projects. Senior Software Engineer at MedTech Global in Melbourne, Australia.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionCCheckComboBox::GetCheck( INT nIndex ) should be constmemberAdi Shavit29-Mar-12 0:23 
Nice class.
One tweak though:
CCheckComboBox::GetCheck( INT nIndex ) 
should be
CCheckComboBox::GetCheck( INT nIndex ) const
Thanks!
Adi
GeneralMy vote of 5memberMember 874321920-Mar-12 15:49 
I spent 3 hours trying to re-size the drop-down size. Microsoft VC 2008 help & internet say use m_comboBoxAudioSource but compiler said does not exist.
Wolfram is my hero!
QuestionHow to reduce height of the combo box?memberonlybj24-Aug-10 5:08 
i can't find way how to change default height of the combo box.
 
How to reduce height of the combo box?
GeneralCombo box is not visible on Vista OS.membersandeep sumbe29-Oct-09 0:55 
I have created Tab dialog having combo box on it.
After closing child dialog, combo box of parenet tab dialog is not visible.
If parent != tab dialog then it shows combo box.
This issue occurs on Vista OS only.
 
Please suggest a good solution.
GeneralFindString() gininf assertion failurememberShashikant_20066-Mar-09 3:39 
Hi I am using CComboBox class and want to detect whether a string is present in a combo box list before adding, I tried to use
 
if(CB_ERR == m_editFindCombo->FindString(-1,str)) , function says if you want to search entire list you need to pass -1,
 
but its giving me debug asertion failure, how can I got through it??
 
Never complain,never explain,just do your work.

QuestionColor of the drop-down button?memberddas-edEN23-Jul-08 23:27 
How is it possible to change the color of the drop-down button on the combo-box?
Is it possible? Sniff | :^)
 

QuestionDrop List issuemember12kaunas16-May-07 15:39 
I want to use combo box in Drop List mode since I don't allow editing. But when I open box it does not display my selected text. After I click and choose any line it does show up in the window. I am using code MyCmbBox.SetWindowText(myText). And it works OK in Drop Down mode. Is this how it designed to work or am I doing anything wrong. I want to fix it, because I need to show some initial text.
Thanks.
AnswerRe: Drop List issuememberWolfram Steinke16-May-07 21:35 
Use MyCmbBox.SelectString(myText) instead. If it finds a match the item will be selected and copied to the edit control.
 
Happy programming!!

GeneralRe: Drop List issuemember12kaunas17-May-07 5:15 
Thanks a lot. This is exactly what I need.Smile | :)
Questionhow to make readonly the combo controlmembermailtochandra2000@yahoo.com3-May-07 18:25 
Iam using Combo control and it is editable ,I need combo control with readonly using VC++6.0,Can you pls help me?
 

 


 
Chandrasekaran.
AnswerRe: how to make readonly the combo controlmemberWolfram Steinke3-May-07 21:12 
Set the the combobox style to CBS_DROPDOWNLIST
 
Happy programming!!

AnswerRe: how to make readonly the combo controlmemberJLINK31-Jan-08 9:00 
I had the same need. I want to have the Edit box but I don't want the user to be able to edit the text but I do want them to be able to select and copy from it. So, if using CBS_DROPDOWNLIST isn't exactly what you wanted, try using GetComboBoxInfo. You'll get a handle to the edit box which you can then send a message to tell it to be ReadOnly like this:
 
extern CComboBox *pMyComboBox;
 
CCOMBOBOXINFO cbInfo;
 
cbInfo.cbSize = sizeof(COMBOBOXINFO);
pMyComboBox->GetComboBoxInf(&cbInfo);
 
::SendMessage(cbInfo.hwndItem, EM_SETREADONLY, (WPARAM)TRUE, 0);
 
-Jim
Questionquestions on OnSimpleEditupdate() & the height of ListboxmemberHunt Chang17-Oct-06 6:52 
Mr. Steinke,
 
Thanks for your great article, it helps me to learn a lot on command the Combo though I have just read it recently.
 
I got 2 questions, the first,
inside the OnSimpleEditupdate(), there is one line of instruction just after the instruction . . . = m_Simple.GetEditSel(),
if ( LOWORD(dwSel) != LOWORD(dwSel) )    return;
according to the explaination of CB_GETEDITSEL from MSDN, the LOWORD(dwSel) points to the strating pos of editing and the HIWORD(dwSel) points to the ending pos. But inside this method, both of them should point to the same position during the user's editing, then I do not get what is the purpose of this line of instruction; once I have thought one of the LOWORD() is a typo of HIWORD(), but it does not make sense either. Sleepy | :zzz:
 
the second question,
when we set the height of the Listbox for the combo's dropdown appearence, I have noticed you are using GetItemHeight(-1) to calculate the line height. Again by MSDN, CB_GETITEMHEIGHT, your instruction GetItemHeight(-1) should return the height of the "selection field" and GetItemHeight(0) returns the height of the "list items". Since we are changing the height of the Listbox of a combo, so I tried to change the code to use GetItemHeight(0) for the calculation, but the result is incorrect, the height setting is shorter than my expectation.
From the logic of view, I thought I am right but I failed, could you please explain the reason why you choose to use GetItemHeight(-1)?
 
Sorry, I am not an English native speaker, so if you found my blind spot, please advise.
 
Best Regards, Rose | [Rose]
Hunt Chang Wink | ;)
AnswerRe: questions on OnSimpleEditupdate() & the height of ListboxmemberWolfram Steinke17-Oct-06 11:28 
With regard to question 1, you are correct, that is a typo.
For question 2 you GetItemHeight(-1) is used because gives the height of the item plus the the gap between the items, that is the height of the "highlight rectangle" when the item is selected. GetItemHeight(0) does not include the the vertical gap and therefore gives an 'incorrect' height.
 
Happy programming!!

QuestionRe: questions on OnSimpleEditupdate() & the height of ListboxmemberHunt Chang19-Oct-06 6:52 
Mr. Steinke,
 
Thanks for your kind & fast explaination.
 
Regarding to the question 1, can you please tell me in what kind of scene it would make the HIWORD(dwSel) != LOWORD(dwSel) ? Big Grin | :-D
 
Wish you happy all the time too.
Hunt Chang Rose | [Rose]
AnswerRe: questions on OnSimpleEditupdate() & the height of Listboxmemberandrewtruckle25-Jan-07 3:35 
Maybe it is caused when you paste in some text into the control?
Questionhow to set the height of the CEdit/CStatic of the combomemberi_a_z21-Jun-06 4:06 
I want to stuff a combo into a list control, but the height of the combo is somewhat larger than the row in the list control. I suspect there's not an easy way to change the height without subclassing and all the jazz. Is this really so bad? D'Oh! | :doh:
AnswerRe: how to set the height of the CEdit/CStatic of the combomemberWolfram Steinke21-Jun-06 8:45 
Have a look at the SetItemHeight method.
 
Happy programming!!
GeneralRe: how to set the height of the CEdit/CStatic of the combomemberesquivec6-Jun-07 5:25 
I tried it and I found that SetItemHeight function works only if the control have one of the CBS_OWNERDRAWxxx styles, but then I have to process WM_MEASSUREITEM and WM_DRAWITEM messages...
 
I think it is a lot of work if the only thing you want to do is changing the height of the Static/Edit area of the combo.

 
Carlos E.
Generalmodal dialogboxes.memberswapna_signsin14-May-06 23:15 
Hi,
How do we get the data from database dynamically into 2nd dlgbox,say d1 and d2 are 2 dlgboxes,of which d1 is main dlgbox.Ican retrieve data into d1 but not into d2.
How could we do it.
 
Thanx
 
swapna_signsin
GeneralRetrive string from comboboxmemberaros_atti8-Dec-05 2:50 
Hello, I would like to know how to efficiently retreive a selected string from a combobox, and store it in a CStrring object.
 
Thanks
GeneralRe: Retrive string from comboboxmemberJohn Simmons / outlaw programmer8-Dec-05 4:01 
That's described in the article.

 
------- sig starts
 
"I've heard some drivers saying, 'We're going too fast here...'. If you're not here to race, go the hell home - don't come here and grumble about going too fast. Why don't you tie a kerosene rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt
 
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
 

QuestionHow do I add variables for the Comboboxmemberkotharibrijesh@yahoo.com5-Sep-05 6:06 
i m a student of engineering college and i would like to know how did u add the variables for it.I m a new VC++ programmer at present and we have this as our subject in this semester.So Please do help.
Thanking u.;)
AnswerRe: How do I add variables for the ComboboxmemberYBH98-Sep-05 1:52 
Just do mouse right click on the combo box and select 'Add Variable' menu item (you should see popup menu near the combo).
 
Yuval
QuestionUsing keystrokes on CComboBox controlsmembergabriel92729-Aug-05 7:47 
I really like using a keyboard character to get to a list item quickly. Is there a way to allow the user to use keyboard functions to get to an item?
 
For example, pressing "k" would skip ahead to items like "kite", "kit", "kid", etc.
 
Also, is there a way to customize the sorting of list items instead of the default alphabetizing of list items?
AnswerRe: Using keystrokes on CComboBox controlsmemberWolfram Steinke29-Aug-05 8:48 
The Dropdown list ComboBox already has this behaviour.
gabriel927 wrote:
For example, pressing "k" would skip ahead to items like "kite", "kit", "kid", etc.
If you need a more complex behaviour I suggest you subclass the ComboBox and override the keystroke handler.
Custom sorting you must do yourself. If you turn the "sort" style off and then add the strings to the lest in order you want them they will stay in that order.
 


 
Happy programming!!
QuestionHow to set the heightmemberjaypt16-Jun-05 21:29 
How to set the height of the dropped rectangle of the
ComboBox in VC++ 6.0 ? I got zero height and do not know
how to enlarge it. Thanks.
AnswerRe: How to set the heightmemberWolfram Steinke17-Jun-05 13:27 
How do it when editing the dialog is described in this article above. You click on the arrow and drag the revealed rectangle to the desired height.
 
At runtime you can do it like this:

void MyComboBoxClass::SetNumberOfLines(int nLines)
{
nLines = min( max(nLine, 1), 7);
CRect rect;
GetWindowRect( &rect (;
rect.bottom = rct.top + nLines * GetItemHeight( -1 ) + rect.Height();
SetWindowRect(NULL, 0, 0, rect.Width(), rect.Height(),
SWP_NOMOVE | SWP_NOZORDER);
}

 
Happy programming!!
GeneralRe: How to set the heightsussstarschen25-Jul-05 19:47 
A bit minor that SetWindowRect must be replaced by SetWindowPosLaugh | :laugh:
GeneralRe: How to set the heightmembersixpence19-Sep-05 23:19 
I just do like above.
 
At runtime, i get the desired height, but there is no scroll bar, so i can't to select the last iterm extend the recttangle?
 
Can you help me?
GeneralRe: How to set the heightmembersixpence19-Sep-05 23:40 
I see.
 
Add the WS_VSCROLL style when create the CComboBox object.
GeneralVScrollmemberSeix5-Jun-06 21:51 
check/uncheck style-property of "Vertical scroll" doesn´t set/reset the WS_VSCROLL-bit.
So, how to get a VScroll-bar when creating a combobox dynamically?
 

GeneralNothing is displayed in the combo boxsussBemineni Srikanth13-Oct-04 23:41 
I am using .net
 
I created a combo box and assigned a varible with the help of the wizard.
nothing is displayed in the combo box even when i add some thing in the data item of the properties window
the same is the case even when i add a string using the addstring method.
 
May i know what is the problem should i intialize something or iam doing the wrong way
GeneralRe: Nothing is displayed in the combo boxsussAnonymous5-Jan-05 10:18 
Change the height of the drop-down. In this article he says to right-click and adjust the drop-down size but at least in VS.NET 2003 you left-click on the drop-down button then adjust the size.
 
Otherwise the drop-down size will be zero and you won't see anything.
 
I just had this problem and ran across this article via Google search.
GeneralError with Addstring &amp; Editablememberrlaley5-Oct-04 17:41 
I create CComboBox with Dropdown style.
 
if (!m_comboBox.Create(CBS_DROPDOWN|CBS_HASSTRINGS|CBS_AUTOHSCROLL|
WS_VISIBLE|WS_VSCROLL|WS_CHILD|WS_TABSTOP|WS_EX_CLIENTEDGE, rc5, this, IDS_TOOLBAR_COMBO))
{
TRACE("Failed to create combo-box\n");
return FALSE;
}
m_comboBox.AddString("Test1");
m_comboBox.SetFont(CFont::FromHandle(static_cast(GetStockObject(DEFAULT_GUI_FONT))));
 
But...
 
When i use Addstring my combobox don't show everything when i click.
and in Edit, i can type text but i can't use Backspace to delete or use Enter. I must use Delete (On keyboard) to delete text.
 
pls!! need help Cry | :((
 

 
rlaley...girl
GeneralRe: Error with Addstring &amp; EditablememberWolfram Steinke8-Oct-04 9:28 
Have a look at the 2 articles below. They take you through the step of uding a ComboBox on a toolbar
 
http://www.codeproject.com/docking/toolbarex.asp
 
http://www.codeproject.com/docking/ctrls_in_tb.asp
 
Happy programming!!
GeneralRe: Error with Addstring &amp; Editablememberrlaley17-Oct-04 19:24 
Confused | :confused: i test my combobox, my combobox can add string but it don't show or list of my combobox is very short. Should i do or config??
 
need help, thx
 
rlaley...girl
GeneralRe: Error with Addstring &amp; Editablememberrlaley18-Oct-04 16:16 
thanks for good tutorial Blush | :O
 
in your tutorial topic "Changing the height of the Dropdown List" Could i config it by coding? i think it was my ploblem.
thanks again Smile | :)
 
rlaley...girl
GeneralRe: Error with Addstring &amp; Editablememberrlaley19-Oct-04 0:21 
OH! i found my misstake, i must config at CRect like this
rc5.left = 48;
rc5.right = rc5.left + 170;
rc5.top = 3;
rc5.bottom = 150; <----Height of list box
 
Now, i has only one ploblem, in Edit control of my combobox can't use Backspace to delete text.
please help!
 
thanks a lot Smile | :)

 
rlaley...girl
GeneralRe: Error with Addstring &amp; EditablememberWolfram Steinke19-Oct-04 0:37 
I not sure why the backspace doesn't work. It should. Have you added any form of key input handler that may be trapping it?
 
Happy programming!!
GeneralRe: Error with Addstring &amp; Editablememberrlaley19-Oct-04 18:04 
Thanks again Smile | :)
 
I read your tutorial and found link to : "Implementing an autocompleting Combobox By Chris Maunder ". I think it can fix my ploblem about Key handler, finaly yor're a good teacher for me Smile | :) .

 
rlaley...girl
GeneralRe: Error with Addstring &amp; EditablememberWolfram Steinke19-Oct-04 0:28 
You can do it programmatically. Here is the code I have used in the Past. Use the Intergral Height style to ensure that all items in the ComboBox have the same height. This height, in pixels, is determined by GetItemHeight( -1 ). In this example the maximum height is limited to 7 items.
 
void CHSelectorCombo::SetNumberOfLines(int nLines) {
nLines = min( max(nLines, 1), 7 );
CRect lprect;
GetWindowRect( &lprect );
lprect.bottom = lprect.top + nLines * GetItemHeight( -1 ) + lprect.Height();
SetWindowPos(NULL, 0, 0, lprect.Width(), lprect.Height(), SWP_NOMOVE | SWP_NOZORDER );
}


 
Happy programming!!
GeneralAfxMessageBox won't popup in Property pagememberChanKarChun28-Sep-04 20:52 
i follow the method of this tutorial, i got everything ok, then i create a property sheet with a few property page(in which i place a combobbox using the same method), the AfxMessageBox then brings the problem, what axactly the problem is?? not a dialog class? how to solve?
GeneralRe: AfxMessageBox won't popup in Property pagememberWolfram Steinke28-Sep-04 21:10 
If you send me the code segment I'll see if I can work it out. You haven't given enough detail here.
 
Happy programming!!
GeneralRe: AfxMessageBox won't popup in Property pagememberChanKarChun29-Sep-04 9:51 
the view class :
 
#include "Manu.h"
#include "Tran.h"
#include "Disp.h"
 
#include "resource.h"
#include "string.h"
.
.
.
int CLCAToolView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CScrollView::OnCreate(lpCreateStruct) == -1)
return -1;

CPropertyPage m_page[3];
UINT rgID[3] = {Tab_Manu, Tab_Tran, Tab_Disp};
for (int i = 0; i < 3; i++)
{
m_page[i].Construct(rgID[i]);
m_sheet.AddPage(&m_page[i]);
}


// Display a modal CPropertySheet dialog.
m_sheet.DoModal();
 
return 0;
}
 
BOOL CLCAToolView::OnEraseBkgnd(CDC* pDC)
{
CPen pen(PS_SOLID,0,GetSysColor(COLOR_BTNFACE));
CPen *pPen =pDC->SelectObject(&pen);
CRect rect;
GetClientRect(&rect);
pDC->Rectangle(rect);
pDC->SelectObject(pPen);
Return TRUE;
}
 
the CPropertyPage class :
#include "resource.h"
#include "string.h"
.
.
void manu::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
DDX_Control(pDX, CBM_ToM, m_CBM_ToM);
DDX_CBIndex(pDX, CBM_ToM, m_CBM_ToMIndex);
//}}AFX_DATA_MAP
}
.
.
ON_CBN_SELCHANGE(CBM_ToM, OnSelchangeMToM)
.
.
void manu::OnSelchangeMToM()
{
// TODO: Add your control notification handler code here
UpdateData();
if( m_CBM_ToMIndex < 0 ) return;
CString str;
m_CBM_ToM.GetLBText( m_CBM_ToMIndex, str );
CString Out;
Out.Format( "Drop List Selection => index %d\n%s",m_CBM_ToMIndex, str );
AfxMessageBox( Out );
}
GeneralRe: AfxMessageBox won't popup in Property pagememberWolfram Steinke2-Oct-04 21:16 
The code looks okay to me but you may like to at the return value from AfxMessageBox which may explain it.
 
Happy programming!!
GeneralcomboxBox and Datagridmemberparrotlabel28-Jun-04 18:55 
Thanks for the tutorial. I try to use Extended combox and the Microsoft DataGrid Control (6.0) together. After I input the string value inside the Extended combox and run it. it gives me the Debug Assertion Failed at file:OCCmgr.cpp line 401. How can the datagrid can not work with the combox?
 
thanks
min
GeneralCComboBox in CView AppmemberDaveIR18-Jun-04 7:44 
I downloaded Wolfram Steinke's CComboBox tutorial and everything worked as expected. That's my problem! I've inserted a Combobox into a dialog box opened from a MFC App window and there's no way I can make the Combo box give me the current selection. Any attempt whatsoever to access the current selection, neither by the (int) variable assosiated with a dropdown list combobox or by the functions assosiated with the CComboBox object ( GetCurSel()) They all provide -1 as a result.
 
I've tried Owner drawn as well, and everything BUT the current selection works as expected.
 
It's got to have something to do with the creation in a child type dialog box.
Help!?

QuestionHow to load bitmap .memberipichet20-May-04 19:24 
Thank you for guiding me on ConboBox.
Now I would like to ask again.
 
How to load bitmap(or Icon) resource ino picture box at run time.
 
Thank you very much.
AnswerRe: How to load bitmap .memberWolfram Steinke20-May-04 23:06 
I suggest you have a look at this link as a starting point
 
http://www.codeproject.com/combobox/iconcombobox.asp
 
It displays Icons in an ownerdrawn combobox.
 
Happy programming!!

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 24 Mar 2001
Article Copyright 2000 by Wolfram Steinke
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid