Click here to Skip to main content
6,630,901 members and growing! (21,405 online)
Email Password   helpLost your password?
Languages » C# » General     Beginner License: The Code Project Open License (CPOL)

Dynamically Adding Button to a Form

By Mark Pryce-Maher

How to dynamically add a button to a windows form
C# 1.0, C# 2.0, Windows, .NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, Dev
Posted:7 Dec 2006
Updated:15 Dec 2006
Views:23,798
Bookmarked:10 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
16 votes for this article.
Popularity: 2.97 Rating: 2.47 out of 5
7 votes, 43.8%
1

2
1 vote, 6.3%
3
2 votes, 12.5%
4
6 votes, 37.5%
5

Introduction

I was writting a small C# application that required buttons to appear depending on a configration file.  I did a quick search of the internet and could not find much, so I thought I would put something simple together. 

Background

The concept of adding a button is exaclty the same as adding any control to a form (win form or WPF form).

Using the code

Below is a simple peice of code that creates an instance of a button, changes some properties and adds it to the form.

// Create Instance of a Button

Button myButton = new Button();

// Set some properties


myButton.Visible = true; 

// Button Size

myButton.Width = 100; 
myButton.Height = 20 

// Positon

myButton.Left = 100; 
myButton.Top = 100; 

myButton.Location = new Point(Left, Top); 

// Give to button a name

myButton.Name = Name; 

// Text to appear on Button

myButton.Text = "My Button"; 

// Make the text look nice

Font myFont = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold); 
myButton.Font = myFont;

// This line adds this instance of a button to the form

this.Controls.Add(myButton);

For WCF we need to do something slightly different, as the object model is different.

// Create my Button

Button myButton = new Button();

// Create a grid to go on the button

Grid subGrid = new Grid();

// Create a text block and image to go on the grid

TextBlock myTextBlock = new TextBlock();
Image myImage = new Image();

// Get an image from a file

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("c:\\mylogo.jpg");
bi.EndInit();
// myImage3.Stretch = Stretch.Fill;

myImage.Source = bi;

//put some text on the button

myTextBlock.Text = "My Button";

// add the image and text bock to the grid

subGrid.Children.Add(myImage);
subGrid.Children.Add(myTextBlock);

// set the grid to the content of the button

myButton.Content = subGrid;

// add the button to a grid on the form called grid1.

grid1.Children.Add(myButton);

Thats okay up to a point, but the button doesn't do anything. We now need to associate the click event with some code.

//

myButton.Click += new System.EventHandler(this.Button_Click_Code);

 // Create a new function

 private void Button_Click_Code(object sender, EventArgs e) 
 {
     MessageBox.Show("You clicked my button");
 }

If you create multiple buttons and assoicate theem with the same Button_Click_Code function, there needs to be some way to work out which button you pressed.

 // Create a new function

 private void Button_Click_Code(object sender, EventArgs e) 
 {
  // Try something like this   

    Button myBut = (Button)sender;
    MessageBox.Show(myBut.Name);

    switch (myBut.Name)
    {
        case "button_one" : 
            // do something

            break;
        case "button_two" :
            // do something else

             break;
        default:
            // everything else

            break;
     }
 }

Points of Interest

The idea of dynamically adding controls to a form is the same as above, any object of any type can be added to a form.

Updates

15/Dec/2006 Added some code for a WPF button

Locations of visitors to this page

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mark Pryce-Maher


Member
I've been a programmer for longer than I care to remember. It all started with those BBC (model B's) at school, it all went down hill from there.....

This year, I am mostly coding in.. C# (WPF & WCF)

Blog Address http://markpm.blogspot.com


Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
  (Refresh) 
-- There are no messages in this forum --

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Dec 2006
Editor:
Copyright 2006 by Mark Pryce-Maher
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project