简体   繁体   中英

how to get numeric value from edit control

Sorry if this is too trivial, but I can't figure out how to get numeric value entered into edit control. MFC edit control represented by CEdit class.

Thank you.

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

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 have to call

UpdateData(TRUE);

in order to write the values from the controls into the variables. Call

UpdateData(FALSE);

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

EDIT (Bonus):

Upon re-reading my answer, I noticed that UpdateData(...) needs a BOOL variable - corrected. So I had an idea for people who like readability. Because I always got confused which call did which direction, you could introduce an enum to make it more readable, like so (maybe in stdafx.h or some central header):

enum UpdateDataDirection
{
    FromVariablesToControls = FALSE,
    FromControlsToVariables = TRUE
}

and you would just have to write:

UpdateData(FromVariablesToControls);

or

UpdateData(FromControlsToVariables);

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

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

If you're going to need that functionality regularly, say on multiple dialogs, then you may as well subclass your own CEdit-derived class for doing the getting, setting and validation work.

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 that, make sure the message map passes along all other messages to the parent CEdit. You could extend it to have customisable lower and upper limit and decimal places setting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM