MFC ComBox and get the item?

I've created a Combo Box in my MFC Dialog and would like to get the integer number which I select, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

void CCOMPort_ReaderDlg::ReadDevice()
{	
	CHAR DeviceTermSize [6];
	
	m_DeviceNumber.ResetContent ();
	
	for ( int nDevice = 1; nDevice <= 8; nDevice++ )
	{
		sprintf ( DeviceTermSize, "%ld", nDevice );

		m_DeviceNumber.AddString ( DeviceTermSize );
	}
	
	m_DeviceNumber.SetCurSel ( 1 );
  
       // int PortNumber = ??? ;

}



I have no problem to select any number from 1 to 8 in the ComboBox but I need to get the number which I select to be applied in the function: CSerialSource::Open(PortNumber); "

This is very important to my serial communication to select the Port Number and let my program know what I have selected.

How can I obtain the "PortNumber" value? Any suggestion and help is well appreciated. Thanks!

Last edited on
Try this method.

I assume that m_DeviceNumber is an MFC CCombobox.

You can associate data with a string item in a Combobox.

The AddString function returns the index of the newly added string within the Combobox.

So:
1
2
3
4
5
6
7
8
9
10
	
for ( int nDevice = 1; nDevice <= 8; nDevice++ )
	{
		int index;
               sprintf ( DeviceTermSize, "%ld", nDevice );

		index = m_DeviceNumber.AddString ( DeviceTermSize );
                m_DeviceNumber.SetItemData(index, (DWORD) nDevice); //**** 

	}


You now have a matched pair of values in the CComboxbox. Only the string is displayed.
But when a user selects a combobox item, you can get the associated data value with
m_DeviceNumber.GetItemData(index) where index is
the index of the selected item.
You get this index using GetCurSel( ) function;

int data =(int) m_DeviceNumber.GetItemData( m_DeviceNumber.GetCurSel());
Last edited on
Thanks for your suggestion. Anyway I've found out another easier way instead of using "GetItemData". I use "GetLBText" which harvest the CString that I select and later convert it to integer number. I've already tried using "GetItemData" but it only retrieves the index, not the actual integer number, for example when I choose 7 it means index 0 while 8 means index 1.

Below is part of my code:

1
2
3
4

m_DeviceNumber.GetLBText( index, strPortText );
int PortIndex = atoi( (LPCTSTR) strPortText );


Hope this can help others as well.

Topic archived. No new replies allowed.