Lecture Set 07XDynamic

advertisement
Dynamically create a collection of buttons
// Creates all buttons in panel for selection of letters
private void createLetterSelectionButtons()
{
Size size = new Size(21, 25);
// Size of each button
Point loc = new Point(0, 0);
// Starting location
int padding = 50;
// Space between each button
for (int i = 0; i <= buttonLetterMax - 1; i++)
{
// iterate through all 26 letters of the alphabet
loc.Y = 10;
// Insert a new letter label
Button thisButton = new Button(); // Instantiate a new button
btnLetter[i] = thisButton;
this.btnLetter[i].AutoSize = false;
this.btnLetter[i].Font =
new System.Drawing.Font("Microsoft Sans Serif", 12.0f,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
System.Convert.ToByte(0));
this.btnLetter[i].Location =
new System.Drawing.Point(10 + i * size.Width + padding, loc.Y);
if (i == 0)
this.btnLetter[i].Name = "btn" + "00";
else if (i <= 9)
this.btnLetter[i].Name = "btn" + "0" + i.ToString();
else
this.btnLetter[i].Name = "btn" + i.ToString();
this.btnLetter[i].Size = size;
this.btnLetter[i].TabIndex = 23;
this.btnLetter[i].Text
= (System.Convert.ToChar('A' + i)).ToString();
// Add this button to the event handler list so that we may use
//
the .Click event for all the buttons in the collection.
// This is very important, make sure you add each individual
// event handler you want to use here
this.btnLetter[i].Click
+= new System.EventHandler(this.ButtonLetter_Click);
// Finally add the control (button) to the pnlBoard
pnlBoard.Controls.Add(btnLetter[i]);
} // end inner for loop
} // end createLetterSectionButtons
Download