/* * __________________________________________________ CREATING CONTROLS & EVENT HANDLERS AT RUNTIME __________________________________________________ This shows how to adjust the form size, create a new button control, and create a click event handler for that new button. * */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Create_Event_Handlers_at_runtime { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //---set form size/position this.Height = 200; this.Width = 400; this.Text = "Creating Controls and Events at Runtime"; //---create a new button Button btn = new Button(); btn.Location = new Point((this.Width - btn.Width) / 2, (this.Height - btn.Height) / 3); //x & y btn.Text = "Click me!"; //---now add an event handler to respond to when the button is clicked btn.Click += ButtonClickHandler; //---add the control to the forms control collection this.Controls.Add(btn); } private void ButtonClickHandler(Object sender, EventArgs e) { Button whichBtn = (Button) sender; MessageBox.Show("You clicked " + whichBtn.Text, "Custom Event Handlers", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }