So I’m making a program and I hit a wall, because I don’t know how to pass a variable from one method to another. To explain the situation, I add the code:
1) I create a toolStripMenuItem^ TestIsvalyti on formload.
private: System::Void Form2_Load(System::Object^ sender, System::EventArgs^ e)
{
MenuStrip^ menu = gcnew MenuStrip;
menu->Location = Point(0,0);
menu->Size = System::Drawing::Size(this->Width, 25);
ToolStripMenuItem^ ElDienynas = gcnew ToolStripMenuItem;
ElDienynas->Text = "El. Dienynas";
menu->Items->Add(ElDienynas);
Controls->Add(menu);
//TESTUI
ToolStripMenuItem^ TestIsvalyti = gcnew ToolStripMenuItem;
TestIsvalyti->Text = "ISVALYTI";
menu->Items->Add(TestIsvalyti);
TestIsvalyti->Click += gcnew EventHandler(this, &Form2::TestIsvalyti_Click);
Controls->Add(menu);
//TESTUI
}
2) I have an event handler, which creates a TabControl^ ElDienynasTab
private: System::Void menuGrupe_Click(Object^ sender, EventArgs^ e)
{
TabControl^ ElDienynasTab = gcnew TabControl;
ElDienynasTab->Location = Point(14, 40);
ElDienynasTab->Size = System::Drawing::Size(768, 500);
Controls->Add(ElDienynasTab);
TabPage^ LankomumasPazymiai = gcnew TabPage;
LankomumasPazymiai->Text = "Lankomumas | Pazymiai";
ElDienynasTab->Controls->Add(LankomumasPazymiai);
TabPage^ namuDarbai = gcnew TabPage;
namuDarbai->Text = "Namu darbai";
ElDienynasTab->Controls->Add(namuDarbai);
}
3) I created another event handler for the TestIsvalyti MenuStripItem, which has to remove the ElDienynasTab from the 2) method, but I hit the wall there because I don’t know how to pass the variable to this event handler.
void TestIsvalyti_Click(System::Object^ sender, System::EventArgs^ e)
{
this->Controls->Remove(ElDienynasTab);
}
Please explain to me how to do it and/or add a piece of code. Thank you very much.
You have two different functions,
menuGrupe_ClickandTestIsvalyti_Click. Functions can’t see local variables within other functions, so you need to increase the visibility of theTabControlif you really want to use that specific instance from another method.Create a field in your form.
Store the TabControl in the field instead of a local variable.
If you drag and drop components onto your form with the designer, you’ll see that this is the pattern that’s followed. In fact, unless there’s some reason you need to dynamically create controls inside your
Form_LoadandmenuGrupe_Clickcalls, you should be using the designer for all of this and not trying to write it yourself. It will put initialization code intoInitializeComponent()and handle the creation of the appropriate fields for you.