Józef Podlecki
Józef Podlecki

Reputation: 11305

How to pass by reference a button's or other control's text

String ^% text = button->Text ; 
text = "something" ;

Should change button's text, but it doesn't.

Upvotes: 0

Views: 103

Answers (1)

Hans Passant
Hans Passant

Reputation: 942197

This cannot work, the code only updates the object. It doesn't reach further than that and also updates the TextBox::Text property. It is not just because this is a string, as hinted in the duplicate link, it won't work for simple value type properties either.

This is because properties are not values, you can't create a reference to them. They look like values from the syntax when you use them. But certainly not when you declare them, note how you have to write a get and a set method. So to update the displayed text in the TextBox you have to call the set method of the property. Which isn't just a simple variable assignment, it is a method call. Intuitively obvious perhaps, note how assigning the Text property has a lot of side effects. You can see it on the screen.

To call a method indirectly you need another vehicle, you need a delegate. Pretty similar to a function pointer in C. Any introductory book about .NET programming will explain them. You can declare your own delegate type, but prefer the generic ones built-in the .NET framework. Add a reference to System.Core so you can use the generic Action<> delegate type. You'll need to first write a method that assigns the Text property:

private: 
    void updateTextBox(String^ text) {
        textBox1->Text = text;
    }

Which would be updated with a sample method like this:

    void Test(Action<String^>^ updater) {
        updater("foo");
    }

And note how this method could update any text box, the delegate object you passed decides which. You create the delegate variable with code like this:

    Test(gcnew Action<String^>(this, &Form1::updateTextBox));

Upvotes: 3

Related Questions