How to get a numeric value from an edit control

Sorry if this is too trivial, but I cannot figure out how to get the numeric value entered in edit control. MFC represented by CEdit .

Thanks.

+8
c ++ windows mfc
source share
3 answers

CEdit comes from CWnd, so it has a member function called GetWindowText , which you can call to get the text in CEdit, and then convert it to a numeric type int or double - depending on what you expect from the user:

 CString text; editControl.GetWindowText(text); //here text should contain the numeric value //all you need to do is to convert it into int/double/whatever 
+8
source share

Besides the already mentioned GetWindowText method, you can also bind it via DDX to the integer / unsigned integer / double / float value. Try the following:

 void CYourAwesomeDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_NUMBER, m_iNumber); } 

whereas m_iNumber is a member of your CYourAwesomeDialog class.

You need to call

 UpdateData(TRUE); 

to write values ​​from controls to variables. Call

 UpdateData(FALSE); 

to do it the other way around - from variables in controls.

EDIT (Bonus):

After reading my answer again, I noticed that UpdateData (...) needs the BOOL variable - fixed. So I got an idea for people who liked readability. Since I was always confused about what call I made in this direction, you could introduce an enumeration to make it more readable, for example (perhaps in stdafx.h or in some kind of central header):

 enum UpdateDataDirection { FromVariablesToControls = FALSE, FromControlsToVariables = TRUE } 

and you just need to write:

 UpdateData(FromVariablesToControls); 

or

 UpdateData(FromControlsToVariables); 
+16
source share

If you need this function on a regular basis, say in several dialog boxes, you can also subclass your own class created by CEdit to perform retrieval, configuration, and validation operations.

 class CFloatEdit : public CEdit { public: CFloatEdit(); void SetValue(double v) { // format v into a string and pass to SetWindowText } double GetValue() { // validate and then return atoi of GetWindowText } void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // only allow digits, period and backspace } }; 

Something like this, make sure the message map goes through all the other messages to the parent CEdit. You can expand it to adjust the lower and upper limit and decimal places.

+1
source share

All Articles