Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How can I create objects out of variable array?
Message
From
14/09/2004 22:32:13
 
 
To
14/09/2004 22:11:41
Czarina Joyce Villanueva
Innovision Systems International
Manila, Philippines
General information
Forum:
ASP.NET
Category:
Other
Miscellaneous
Thread ID:
00942202
Message ID:
00942221
Views:
20
Czarina,

Here's how I do it. This works for me, though there may be other ways to do it. I'll create 5 buttons on the fly, and create an event handler for the click event. The event will display the name of the button that was clicked.
int nNumber = 5;    // # of buttons to add

ArrayList aButtons = new ArrayList();

for(int nCtr=0;nCtr<nNumber;nCtr++) {
   int nVerticalPos = 35 * (nCtr+1);       to create them at a certain vertical offset
   System.Windows.Forms.Button oButton = new System.Windows.Forms.Button();
   oButton.Top = nVerticalPos;
   oButton.Name = "MyButton" + nCtr.ToString();    // create a name
   oButton.Left = 15 ;
   oButton.Text = "Button #" +  nCtr.ToString();    // sample caption
   aButtons.Add(oButton);                           // add the object to an arraylist that I may use later
   this.Controls.Add(oButton);                      // add the control to the form 
   oButton.Click += new EventHandler(MyHandler);    // set up a handler for the click event
 }

private void MyHandler(object sender, System.EventArgs e)
{
	System.Windows.Forms.Button oButton = (System.Windows.Forms.Button)sender;
	MessageBox.Show(oButton.Name.ToString());
}
The arraylist is just in case I need to iterate through the controls. Also, you need to do 'this.controls.add()', to add the buttons to the form.

There may be better ways to do this, this is pretty basic, but it does work. I've never tried the object array that you described - maybe that would be more elegant, but I've never tried it.

(I've never explicitly used this for buttons, I've used it more to instantiate labels and textboxes when there's a need for dynamic data entry).

Hope this helps...
Kevin
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform