Click to See Complete Forum and Search --> : Custom Buttom Class Initializing Oddly


Kiryojo
July 26th, 2007, 08:24 PM
I'm using a custom button class that is initialized by a custom panel class, and for some reason it doesn't initialize properly. Here's the code first, I'll explain the behavior afterwards.


public ref class customButton: System::Windows::Forms::Button
{
public:
static int bar;

customButton(int foo)
{
this->bar = foo;
this->Width = 50;
this->Height = 20;
this->Location = System::Drawing::Point(0,this->bar*32);
this->Paint += gcnew
System::Windows::Forms::PaintEventHandler(this, &customButton::cb_Paint);
}

void cb_Paint(System::Object^, System::Windows::Forms::PaintEventArgs ^)
{
this->Text = this->bar.ToString() ;
}
};

public ref class customPanel: System::Windows::Forms::Panel
{
public:
static array<customButton^>^ myButtons = gcnew array<customButton^>(8);

customPanel()
{
this->Height = 256;
for(int i = 0; i < 8; i++)
{
myButtons[i] = gcnew customButton(i);
}
this->Controls->AddRange(myButtons);
}
};



In my customPanel class I initialize an array called myButtons, and that array stores 8 customButton, which is a custom button class I made. That custom button class stores a variable "foo", which is set when the constructor is called.

Here's the odd behavior: when the loop in customPanel's constructor finishes going, all 8 buttons have the same value of "foo", which happens to be the last value called in the loop. Now, if I manually declare each of the buttons like this:


myButtons[0] = gcnew customButton(0);
myButtons[1] = gcnew customButton(1);
myButtons[2] = gcnew customButton(2);
myButtons[3] = gcnew customButton(3);
myButtons[4] = gcnew customButton(4);
myButtons[5] = gcnew customButton(5);
myButtons[6] = gcnew customButton(6);
myButtons[7] = gcnew customButton(7);


I still have the same problem. All of the buttons have the same foo value as the last button declared. So if I declare "myButtons[6] = gcnew customButtom(5000);" last, all my buttons now have a foo value of 5000. This is not the behavior I want; I want each button to have the foo value it was initialized too.

One other sidenote: The code I used to initialize the buttons locations puts the buttons in the correct y value (which is this->bar * 32 in my code), which means that each of those custom buttons have the correct value in them when they are first initialized.

Anyone have any idea what I'm missing here?

TheCPUWizard
July 27th, 2007, 08:11 AM
static int bar;