Search code examples
visual-studiovisual-c++c++-cli

C++/CLI: Change Property of a dynamically added control at Runtime


I have seen it working with C# but not in Visual C++ 2015

System::Windows::Forms::Label^ mylabel= (gcnew System::Windows::Forms::Label());
mylabel->Name = L"pole";
mylabel->Text = "Hello";
this->Controls->Add(mylabel);

Note that mylabel is a temporary variable here. Now the code work for C#

Control cc = this.Controls.Find("pole", true).First();
cc.text="New";

And I've tried this as there is no .First() or ->first(),

Control^ x = this->Controls->Find(L"pole", true);

and definitely an error shows

`cli::array<System::Windows::Forms::Control ^, 1> ^" cannot be used to initialize an entity of type "System::Windows::Forms::Control ^`"

How can I get that object as Control in runtime?


Solution

  • The Find method returns an array. In your C# example you call First() which returns the first item in the array (returning a reference to the Control). In the C++ example you do not call First() or do anything to retrieve a single item. That is why the error message indicates that you can't convert and array (note cli::array in error) to a Control reference.