Posted on 2007-02-28 10:29 Tauruser
阅读(18518) 评论(1) 编辑 收藏 引用
MFC ComboBox 使用方法（转载）
Combo box controls are space savers. Wherever there is no need for a multi-select from a list of items, combo box is a good choice in such places. This article " CComboBox Example" explains how to use the MFC CComboBox class for manipulation of a list of strings.
CComboBox Example - Initializing a Combo Box:
It is assumed that the readers of the sample have already created a dialog box (either in a dialog based application or SDI/MDI application) and placed a combo box control from the controls toolbox on the Resource Editor.
After placing the combo box control on the dialog box, open the class wizard by pressing Ctrl + W keys or Menu --> View --> ClassWizard. In the Member Variables tab, Add a Variable for the CComboBox class. This CComboBox example assumes that the variable name is,
This m_cbExample will be used further in our CComboBox example MFC code.
CComboBox Example - Adding Items to a Combo Box:
The function AddString is used for adding items to a combo box. If there is a constant set of data, these values can also be added in the Resource Editor itself. The Combo Box control properties dialog has a tab for adding data. Otherwise the data can be added as follows.
CComboBox Example - Retrieving Items from a Combo Box:
a requirement for retrieving items from the combo box will arise from selecting the data. This article also assumes the same. Now the data selected in a combo box needs to be retrieved.
To do this, the first step is to find out the index of the selected item inside the combo box control.
Then the item at the corresponding position needs to be pulled out as follows.
int nIndex = m_cbExample.GetCurSel();
In the above CComboBox example code, the value will be retrieved and stored in strCBText variable. There is another overloaded version for GetLBText. But the version which uses CString is the easiest one.
CComboBox Example - Finding Items inside a Combo Box:
This kind of Find operations on a Combo box will most probably be useful in programs that dynamically modify the values in a combo box. The function FindStringExact is used to find the exact string match inside a combo box.
int nIndex = m_cbExample.FindStringExact(0, "Value to be found");
The string position inside the combo box control is the return value. It returns CB_ERR if it was unsuccessful in finding the string.
CComboBox Example - Deleting Items from a Combo Box:
This operation can be done by using the CCombobox member function DeleteString. This function needs the index of the item inside the combo box.