如何从编辑控件获取数值
how to get numeric value from edit control
抱歉,如果这太微不足道了,但我无法弄清楚如何将数值输入到编辑控件中。由 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 中的文本,然后将其转换为数字类型、int
或double
- 具体取决于您希望用户输入的内容:
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。您可以将其扩展为具有可自定义的下限和上限以及小数位设置。
相关文章:
- 如何在 SCIP C++ 接口中获取 MILP 约束矩阵中的系数值
- 从两个 4x64 位整数数组中获取取模
- 为什么 rapidjson 无法获取此整数值
- 如何获取C++中的输入并将其"split"到列表中?换句话说,取 N 个输入并放入 N 长度的数组中
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- (C++) 取字符串的每个字符并将其放入数组中并获取所述数组的大小?
- 检测/获取捕获的 lambda 函数值
- 如何使用CIN将输入整数值获取到char类型变量中
- 从参考中获取的指针可以在定义明确的C 中取无效
- 在C 中获取Ncurses Chtype或未符号字符的整数值
- 从C 中的PHP扩展中获取函数参数值
- 在编译时间之前抓取常数值
- 从C 中的二进制文件获取整数值时
- 如何从QSpinBox更改的值中获取整数值
- 如何使用 libclang 获取枚举元素的数值?
- C++ 如何从一个整数值中获取三个单独的日期值(日、月、年)
- 如何从编辑控件获取数值
- 如何使用提升程序选项获取默认参数值
- 从c++的树项中获取参数值
- 在c++中从字符串中获取整数值