Suppose we need to enter some float values in UI. If we set “Number” property of Edit control true then it will not allow to enter “.” and hence we can not enter a float value. On the other hand if we allow string then we need to check all possibilities of the characters in the string.
Following is a simple and fast solution for the above problem :
Let the ID of Editcontrol be IDC_VALUE_EDIT
1. Go into the properties window for Editcontrol and from Control Events add “EN_CHANGE” event. It will notify whenever the text will change in the Editcontrol.
2. In void CMyDialog::OnEnChangeValueEdit() defination write following code
CStringvalue; m_ValueEditBox.GetWindowText(value); //m_ValueEditBox is a variable for EditControl //Cursor position in Edit Control int lastSel = m_ValueEditBox .GetSel(); if(ValidateDoubleString(value)) { m_ValueText = value; //m_ValueText is a variable of type CString to hold old value of EditControl } else { m_ValueEditBox .SetWindowText( m_ValueText ); //Setting the cursor position to previous position /* This step is very important, because if it is not written then cursor will move to left or right after above step depending whether the text is left or right aligned.*/ m_ValueEditBox .SetSel(lastSel); } 3. Now write a function to validate that entered string is a float value or a string. bool CMyDialog::ValidateDoubleString(CString value) { bool stringShouldChange = true; LPTSTR invalidStr; // The code will return double value from the string and if any other characters are left after extracting double value, they will be stored in invalidStr double doubleValue = _tcstod(value, &invalidStr); if(*invalidStr) { stringShouldChange = false; } return stringShouldChange; }