Tuesday, September 29, 2009

Create Controls At Runtime in C#

//form level declaration
private Button btnClickableButton;
private PictureBox picBox;
private TextBox txtRunningText;
-------------------------------------------------------------

private void btnAddPictureBox_Click(object sender, EventArgs e)
{
   picBox = new PictureBox();
   picBox.Image = Image.FromFile(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg");
   picBox.Top = 5;
   picBox.Left = 5;
   picBox.Width = 100;
   picBox.Height = 100;
   picBox.SizeMode = PictureBoxSizeMode.StretchImage;
   Controls.Add(picBox);
}
-------------------------------------------------------------
private void btnAddText_Click(object sender, EventArgs e)
{
   txtRunningText = new TextBox();
   txtRunningText.Text = "I am running around!";
   txtRunningText.Top = 5;
   txtRunningText.Left = 110;
   Controls.Add(txtRunningText);

}
-------------------------------------------------------------
private void btnClearForm_Click(object sender, EventArgs e)
{
   Controls.Clear();
}
-------------------------------------------------------------
private void btnAddCLickableButton_Click(object sender, EventArgs e)
{
   EventHandler handler = new EventHandler(btnClickableButton_Click);
   btnClickableButton = new Button();
   btnClickableButton.Click += handler;
   btnClickableButton.Text = "Click Me Please!";
   btnClickableButton.Top = 5;
   btnClickableButton.Left = 215;
   Controls.Add(btnClickableButton);
}
-------------------------------------------------------------
private void btnClickableButton_Click(object sender, EventArgs e)
{
   MessageBox.Show("Yippee! You clicked me!");
}
-------------------------------------------------------------
*** end of program ***

No comments:

Post a Comment