C# Logo C# WinForms Basics

Introduction to C# WinForms Basics

Windows Forms (WinForms) is a UI framework for creating desktop applications on the Windows platform using the .NET framework. It provides a rich set of controls that allow you to build sophisticated user interfaces with relative ease.

Key Concepts

Creating Your First WinForms Application

You can create a new WinForms project in Visual Studio. This typically involves:

  1. Opening Visual Studio.
  2. Selecting "Create a new project".
  3. Choosing the "Windows Forms App (.NET Framework)" or "Windows Forms App" template (depending on your .NET version).
  4. Naming your project and selecting a location.

The Form Designer

Visual Studio provides a visual designer where you can drag and drop controls onto your form and set their properties. The corresponding C# code for the form's structure and initial setup is generated automatically.

Example: Adding a Button and a Label

Let's say you have a default form (`Form1`). You can add a button and a label:

  1. Open the Toolbox (View > Toolbox).
  2. Drag a Button control onto your form.
  3. Drag a Label control onto your form.

In the Properties window (View > Properties Window), you can change their:

Handling Events (Button Click)

To make the button do something, we need to handle its Click event. Double-click the button in the designer, and Visual Studio will automatically generate an event handler method in your form's code-behind file (e.g., Form1.cs).


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

    private void myButton_Click(object sender, EventArgs e)
    {
        // This code will execute when the button is clicked.
        myLabel.Text = "Button was clicked!";
    }
}
        

The myLabel.Text = "Button was clicked!"; line updates the text property of the label control when the button is clicked.

Commonly Used Controls

Label

Displays static text.

System.Windows.Forms.Label

TextBox

Allows user input of text.

System.Windows.Forms.TextBox

Button

Triggers an action when clicked.

System.Windows.Forms.Button

CheckBox

Represents a boolean state (checked/unchecked).

System.Windows.Forms.CheckBox

RadioButton

Allows selection of one option from a group.

System.Windows.Forms.RadioButton

ListBox

Displays a list of items from which the user can select.

System.Windows.Forms.ListBox

Next Steps

Explore other controls, learn about layout management, and delve deeper into event handling to build more complex and interactive desktop applications.

Related Topics: WinForms Controls WinForms Layouts WinForms Events