如何从编辑控件获取数值

how to get numeric value from edit control

本文关键字:获取 取数值 控件 编辑      更新时间:2023-10-16

抱歉,如果这太微不足道了,但我无法弄清楚如何将数值输入到编辑控件中。由 CEdit 类表示的 MFC 编辑控件。

谢谢。

除了已经提到的GetWindowText方法之外,您还可以通过DDX将其绑定到整数/无符号整数/双精度/浮点值。试试这个:

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

而m_iNumber是你的CYourAwesomeDialog类的成员。

你必须打电话

UpdateData(TRUE);

为了将控件中的值写入变量。叫

UpdateData(FALSE);

以相反的方式执行此操作 - 从控件中的变量。

编辑(奖金):

在重新阅读我的答案时,我注意到 UpdateData(...) 需要一个 BOOL 变量 - 更正。所以我对那些喜欢可读性的人有一个想法。因为我总是对哪个调用哪个方向感到困惑,所以您可以引入一个枚举以使其更具可读性,如下所示(可能在 stdafx.h 或某个中心标头中):

enum UpdateDataDirection
{
    FromVariablesToControls = FALSE,
    FromControlsToVariables = TRUE
}

你只需要写:

UpdateData(FromVariablesToControls);

UpdateData(FromControlsToVariables);

CEdit 源自 CWnd,因此它具有一个名为 GetWindowText 的成员函数,您可以调用该函数来获取 CEdit 中的文本,然后将其转换为数字类型、intdouble - 具体取决于您希望用户输入的内容:

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

如果你要定期需要该功能,比如在多个对话框中,那么你不妨子类化你自己的CEdit派生类来执行获取、设置和验证工作。

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
        }
};

类似的事情,确保消息映射将所有其他消息传递到父 CEdit。您可以将其扩展为具有可自定义的下限和上限以及小数位设置。