Today, I will focus on how to create button in .NET. As we all know that a user control can be created in both design-time and run-time.
Create button at design-time
This is not the point of this post, as we all know: To create a button control at design-time, you simply drag and drop a
Label control from Toolbox to a Form. After you drag and drop a Label on
a Form. After then you can move it around and resize it using mouse and
set its properties and events.
Create button at run-time
This is the focus of my post. To dinamicly create a button in .NET
1. Create an instance of Button class
Button dynamicButton = new Button();
2. Set Button class properties
dynamicButton.Location = new Point(30, 70);
dynamicButton.Height = 50;
dynamicButton.Width = 300;
// Set background and foreground
dynamicButton.BackColor = Color.Red;
dynamicButton.ForeColor = Color.Blue;
dynamicButton.Text = "I am Dynamic Button";
dynamicButton.Name = "DynamicButton";
dynamicButton.Font = new Font("Georgia", 16);
3. Add Button control
A Button control is used to process the button click event. We can attach a button click event handler at run-time by setting its Click event to an EventHandler obect. The EventHandler takes a parameter of an event handler. The Click event is attached in the following code snippet.
// Add a Button Click Event handler
dynamicButton.Click += new EventHandler(DynamicButton_Click);
Now the last step is adding a Button control to the Form. The Form.Controls.Add method is used to add a control to a Form. The following code snippet adds a Button control to the current Form.
Controls.Add(dynamicButton)
No comments:
Post a Comment