Lets say i have an edit control in my program. When i run the program i can write some text in it. How can i save/convert the text that was written in the control to a CString variable ?(it should be "saved" by clicking on a button)

8 Years
Discussion Span
Last Post by mitrmkar

You have at least two choices:

1) Use ClassWizard to give the edit control a variable name. Menu View --> Class Wizzard, elect the control id then Add Variable. For an edit control that will create a CString object which will be filled when UpdateData(TRUE) is called.

2) Get the CWnd* pointer to the control. GetWindowText() returns CString. In below IDC_EDIT1 is the id number of the edit control and yous might be different. Check resource.h for the correct control id or you can view it in ClassWizzard.

CString CTestmfcDlg::GetText()
	CWnd* pWnd = GetDlgItem(IDC_EDIT1);
		return pWnd->GetWindowText();
	return "";

I tried your 2nd solution, but it seems that GetWindowText wants some arguments. What are they supposed to be?


Yes I made an error in my code. MSDN is the official source for help on all win32 api functions. Here's the link for GetWindowText(). You should always check MSDN before using win32 api and MFC functions/classes.


Ok, i think i got it to work now. Did a few modifications though.

Now i have another question. I'm trying to write the text to a file (basicly i'm saving the text file). Here's what i got so far:

CString str;
ec.GetWindowText(str); //ec is the control variable of my edit control
ofstream data("...");

The problem is it seems to write the address of the string to the file. What am i doing wrong?


ofstream is unaware of the CString type, you can cast the CString...

ofstream data("...");
data<< (LPCTSTR) str;

That didn't quite work as i wanted, but i found another solution now anyway. Still, thanks for your answer.


That didn't quite work as i wanted

Sounds a bit odd, because the (LPCTSTR) cast effectively gives you a 'const char *', hence enabling to output the whole string to the ofstream.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.