How to assign a 'char *' to a text property of a control

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi, I'm new at Visual C++ and I can't figure out how to change the text
property of a label. I'm using a char[] variable that I'd like to assign to
the label. Perhaps I should use a System::String^ instead? But when I try
that, I get an error that I can't use a System::String^ as a global or static
variable. What I want to be able to do is the change say the third character
of the text in the text property of the label control from, say, 'k' to 'm'.
Maybe there's a very simple way to do this.
 
Steven said:
Hi, I'm new at Visual C++ and I can't figure out how to change the text
property of a label. I'm using a char[] variable that I'd like to assign
to
the label. Perhaps I should use a System::String^ instead? But when I try
that, I get an error that I can't use a System::String^ as a global or
static
variable. What I want to be able to do is the change say the third
character
of the text in the text property of the label control from, say, 'k' to
'm'.
Maybe there's a very simple way to do this.

There's a String constructor that accepts a C++ char (.NET SByte), so:

char* the_text = "Some ordinary string here."
label1->Text = gcnew String(the_text);

However, that's going to do an ASCII->Unicode conversion. You may be
happier using .NET Char (C++ wchar_t) arrays. To do that you have to write
your string literals like L"string" and character literals like L'm'.

Getting to individual (Unicode) characters of .NET Strings is easy:

interior_ptr<wchar_t> unistr = PtrToStringChars(label->Text);

To do the simple replacement you mentioned, you might do:

array<wchar_t>^ s = label->Text->ToCharArray();
if (s[2] == L'k') s[2] == L'm';
label->Text = new String(s);
 
You don't say what environment you are using? Is this managed or unmanaged
code? If managed, look at Ben Voigt's reply. If not, you are dealing with
window handles. Now, are you doing raw C++, ATL, WTL, or MFC? If the former,
investigate SetWindowText(hwnd, "here is a string").

/steveA
 
Back
Top