Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get numeric value from edit control

Tags:

c++

windows

mfc

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.

like image 596
pic11 Avatar asked May 07 '12 06:05

pic11


People also ask

How do I get value from edit box?

If you want to retrieve the value of an edit box, call the CWnd::GetWindowText() method. If you want to display or change the text of an edit box, call the CWnd::SetWindowText() method. The SetWindowText() method takes a constant pointer to null-terminated string (LPCTSTR) and displays its value in the edit.

How do I get text from edit control in win32?

To retrieve all text from an edit control, first use the GetWindowTextLength function or the WM_GETTEXTLENGTH message to determine the size of buffer needed to contain the text. Next, retrieve the text by using the GetWindowText function, the GetDlgItemText function, or the WM_GETTEXT message.


2 Answers

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
like image 135
Nawaz Avatar answered Sep 23 '22 15:09

Nawaz


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);
like image 20
CppChris Avatar answered Sep 26 '22 15:09

CppChris