Hey guys, sorry if this is a silly question but I have a piece of code which contains something like this:

private: void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button2_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button3_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button4_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button5_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button6_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button7_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button8_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button9_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
private: void button10_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )

This is just an example, not my actual code but the principle is the same. I have several buttons which do the same thing as one another. Instead of just writing a line for each one, is it possible to use a loop of some sort?

E.G something like this:

for(int i=0;i<10;i++)
{
   private: void button[i]_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) 

}

But not actually this as last time I checked, this method doesn't work.

Sorry again if this is a silly question but any answers would be greatly appreciated.

Thanks in advance.

No, not a silly question at all. In your Form1.h, look about halfway down and you'll see the event handler "hookup" with the click event for each:

// button1
		// 
this->button1->Location = System::Drawing::Point(433, 290);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"button1";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);

Use whatever method you want in the &Form1::button1_Click portion (it has to be a function with the same prototype as the click handler, that is with the object, EventArgs signature). Any one of your _Click methods will do. So say you had:

private: System::Void AllButtons_Click(System::Object^  sender, System::EventArgs^  e) {
				 //yada yada
				 }

You'd go through each of your buttons and change the last line of each of them to this->button1->Click += gcnew System::EventHandler(this, &Form1::AllButtons_Click); erasing the old buttonN_Click name.

The loop structure doesn't work because these methods are not meant to be invoked, but to respond to a event that happens in the window.

Edited 5 Years Ago by jonsca: n/a

You sir, have been extremely helpful to me, thank you very much, I really appreciate your help!

This question has already been answered. Start a new discussion instead.