How to Use Form Load and Button click Event in C#

By FoxLearn 7/20/2024 3:23:53 AM   26.03K
In C#, you typically handle events like Form Load and Button Click within a Windows Forms application.

Below is an example that demonstrates how to create a simple Windows Forms application with a Form Load event and a Button Click event.

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "FormLoadAndButtonClick" and then click OK

In the designer view, Drag and drop the Label, Button controls from the Toolbox onto the form, you can design your form as shown below.

button click c#

Double-click on the form to create the Form1_Load event handler.

Double-click on the button to create the btnClear_ClickbtnExit_Click, btnClickMe_Click event handler.

Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormLoadAndButtonClick
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Set text to lblFormLoad label on Form_Load event
            lblFormLoad.Text = "This text is set on startup !";
        }

        private void btnClickMe_Click(object sender, EventArgs e)
        {
            //Set text to lblButtonClick on button click event
            lblButtonCLick.Text = "This text is set on button click !";
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            lblButtonCLick.Text = string.Empty;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            //Exit your application
            Application.Exit();
        }
    }
}

VIDEO TUTORIAL