Introduction
I was writing a small C# application that required buttons to appear depending on a configuration 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 exactly the same as adding any control to a form (WinForms or WPF form).
Using the Code
Below is a simple piece of code that creates an instance of a button, changes some properties, and adds it to the form.
Button myButton = new Button();
myButton.Visible = true;
myButton.Width = 100;
myButton.Height = 20
myButton.Left = 100;
myButton.Top = 100;
myButton.Location = new Point(Left, Top);
myButton.Name = Name;
myButton.Text = "My Button";
Font myFont = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);
myButton.Font = myFont;
this.Controls.Add(myButton);
For WCF, we need to do something slightly different, as the object model is different.
Button myButton = new Button();
Grid subGrid = new Grid();
TextBlock myTextBlock = new TextBlock();
Image myImage = new Image();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("c:\\mylogo.jpg");
bi.EndInit();
myImage.Source = bi;
myTextBlock.Text = "My Button";
subGrid.Children.Add(myImage);
subGrid.Children.Add(myTextBlock);
myButton.Content = subGrid;
grid1.Children.Add(myButton);
That's 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);
private void Button_Click_Code(object sender, EventArgs e)
{
MessageBox.Show("You clicked my button");
}
If you create multiple buttons and associate them with the same Button_Click_Code
function, there needs to be some way to work out which button you pressed.
private void Button_Click_Code(object sender, EventArgs e)
{
Button myBut = (Button)sender;
MessageBox.Show(myBut.Name);
switch (myBut.Name)
{
case "button_one" :
break;
case "button_two" :
break;
default:
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.