Search code examples
winformsvisual-studio-2010c++-cliheader-files

Change label text from different header file, Visual C++ 2010?


I am using Visual C++ 2010 Express. I have a form (Form1.h) that contains a button (btn1) and a label (label1).

When I click the button, I would like to call a function from a different header file (testing.h) that will then proceed to change the text in the label.

What I have is something like this...

Form1.h

#include "testing.h"

... standard form code generated by Visual Studio

private: System::Windows::Forms::Label^  label1;

...

private: System::Void btn1_Click(System::Object^  sender, System::EventArgs^  e) {
        testfunc1();
    }
};

Where testing.h is something like...

#ifndef _TESTING_FUNCS
#define _TESTING_FUNCS

void testfunc1(){
    label1->Text = "Text has been changed from outside.";
}

#endif

When I try to compile and run it, I get errors saying that 'label1' is an undeclared identifier (within testing.h), and an error referring to the "left of '->Text' must point to class/struct/..."

I am new to C++ and usually use Java, so there are a few new things for me here. To me, there are two obvious options:

1) Pass the label to the function as an argument

2) Somehow access the label from the testing.h header file, sans reference

But I'm not really sure how to do either.


Solution

  • The label is a private variable of a class and just like in Java is not accessible from the outside, especially not in static context. You can pass the label, or you can create an accessor function in your Form and pass the whole form.

    Example for passing the label:

    void testfunc1(System::Windows::Forms::Label^ someLabel)
    {
        someLabel->Text = "Text has been changed from outside.";
    }
    

    Calling it:

    System::Void btn1_Click(System::Object^  sender, System::EventArgs^  e) 
    {
        testfunc1(label1);
    }