Getting edit box text from a modal MFC dialog after it is closed

24,747

Solution 1

The dialog and its controls is not created until you call DoModal() and as already pointed, is destroyed already by the time DoModal() returns. Because of that you cannot call GetDlgItem() neither before, nor after DoModal(). The solution to pass or retrieve data to a control, is to use a variable in the class. You can set it when you create the class instance, before the call to DoModal(). In OnInitDialog() you put in the control the value of the variable. Then, when the window is destroyed, you get the value from the control and put it into the variable. Then you read the variable from the calling context.

Something like this (notice I typed it directly in the browser, so there might be errors):

class CMyDialog : CDialog
{
  CString m_value;
public:  
  CString GetValue() const {return m_value;}
  void SetValue(const CString& value) {m_value = value;}

  virtual BOOL OnInitDialog();
  virtual BOOL DestroyWindow( );
}

BOOL CMyDialog::OnInitDialog()
{
  CDialog::OnInitDialog();

  SetDlgItemText(IDC_EDIT1, m_value);

  return TRUE;
}

BOOL CMyDialog::DestroyWindow()
{
  GetDlgItemText(IDC_EDIT1, m_value);

  return CDialog::DestroyWindow();
}

Then you can use it like this:

CMyDialog dlg;

dlg.SetValue("stackoverflow");

dlg.DoModal();

CString response = dlg.GetValue();

Solution 2

  1. Open your dialog resource, right-click on the textbox and choose "Add variable", pick value-type and CString
  2. In the dialog-class: before closing, call UpdateData(TRUE)
  3. Outside the dialog:

    CPreparationDlg dlg(AfxGetMainWnd());
    
    dlg.m_myVariableName = "my Value"; 
    
    dlg.DoModal();
    

    // the new value is still in dlg.m_myVariableName

Share:
24,747
abhinav
Author by

abhinav

Updated on January 29, 2021

Comments

  • abhinav
    abhinav over 3 years

    From a modal MFC dialog, I want to extract text from an edit box after the dialog is closed. I attempted this:

    CPreparationDlg Dlg;
    CString m_str;
    
    m_pMainWnd = &Dlg;
    Dlg.DoModal();
    CWnd *pMyDialog=AfxGetMainWnd();
    CWnd *pWnd=pMyDialog->GetDlgItem(IDC_EDIT1);
    pWnd->SetWindowText("huha max");
    return TRUE;
    

    It does not work.

  • abhinav
    abhinav about 13 years
    thnx for your comment,i am very much new to this vc++ mfc, i have removed that line even then it is not running can you point out another way to extract data from a field
  • abhinav
    abhinav about 13 years
    it is not running from here ASSERT(::IsWindow(m_hWnd));
  • abhinav
    abhinav about 13 years
    it is not running because of this error ASSERT(::IsWindow(m_hWnd));
  • Aidan Ryan
    Aidan Ryan about 13 years
    @abhinav there is a tick mark you can click to express that sentiment