Skip to main content

.NET Controls

Introduction

.NET Controls are the building blocks of graphical user interfaces (GUI) in desktop applications developed using Microsoft's .NET framework. Whether you're working with Windows Forms (WinForms) or Windows Presentation Foundation (WPF), controls provide the interactive elements that users interact with — buttons, text boxes, labels, dropdown menus, and much more.

In this guide, we'll explore what .NET controls are, how they work, and how to implement them in your desktop applications. As a beginner to .NET desktop development, understanding controls is essential as they form the foundation of user interface design.

What Are .NET Controls?

Controls in .NET are UI elements that:

  1. Display information to users
  2. Allow users to input data
  3. Trigger actions when interacted with
  4. Create visual structure for applications

Each control in .NET is essentially an object with properties (appearance and behavior settings), methods (actions the control can perform), and events (responses to user interactions or system changes).

Common .NET Controls Overview

Let's explore some of the most frequently used controls in .NET applications:

Basic Controls

ControlPurpose
ButtonTriggers an action when clicked
LabelDisplays static text
TextBoxAllows users to enter and edit text
CheckBoxEnables boolean (true/false) selections
RadioButtonProvides mutually exclusive options
ComboBoxCreates dropdown selection lists
ListBoxDisplays scrollable item lists
PictureBoxShows images

Control Frameworks: WinForms vs WPF

.NET provides two primary frameworks for creating desktop applications, each with its own control implementation:

Windows Forms (WinForms)

  • Traditional, event-driven framework
  • Simpler and more straightforward for beginners
  • Controls are based on GDI+ rendering

Windows Presentation Foundation (WPF)

  • Modern, XAML-based UI framework
  • More powerful styling and customization options
  • Controls use DirectX rendering for better graphical performance

Working with Controls in Windows Forms

Let's start with the basics of implementing controls in a Windows Forms application.

Creating a Simple Form with Controls

csharp
using System;
using System.Windows.Forms;

namespace SimpleControlsDemo
{
public class MainForm : Form
{
// Declaring controls
private Button submitButton;
private TextBox nameTextBox;
private Label promptLabel;
private Label resultLabel;

public MainForm()
{
// Form setup
this.Text = "My First Controls App";
this.Size = new System.Drawing.Size(400, 300);

// Initialize and configure controls
InitializeControls();

// Add controls to the form
this.Controls.Add(promptLabel);
this.Controls.Add(nameTextBox);
this.Controls.Add(submitButton);
this.Controls.Add(resultLabel);
}

private void InitializeControls()
{
// Label to prompt user
promptLabel = new Label
{
Text = "Enter your name:",
Location = new System.Drawing.Point(20, 30),
Size = new System.Drawing.Size(100, 20)
};

// TextBox for name input
nameTextBox = new TextBox
{
Location = new System.Drawing.Point(130, 30),
Size = new System.Drawing.Size(200, 20)
};

// Button to submit
submitButton = new Button
{
Text = "Say Hello",
Location = new System.Drawing.Point(130, 70),
Size = new System.Drawing.Size(100, 30)
};

// Result label (initially empty)
resultLabel = new Label
{
Text = "",
Location = new System.Drawing.Point(130, 120),
Size = new System.Drawing.Size(200, 20)
};

// Wire up event handler for button click
submitButton.Click += SubmitButton_Click;
}

private void SubmitButton_Click(object sender, EventArgs e)
{
// When button is clicked, update the result label
if (!string.IsNullOrEmpty(nameTextBox.Text))
{
resultLabel.Text = $"Hello, {nameTextBox.Text}!";
}
else
{
resultLabel.Text = "Please enter a name first.";
}
}

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
}

When you run this code, you'll get a simple form with:

  • A label prompting for a name
  • A text box to enter the name
  • A button to submit
  • A result label that displays a greeting after clicking the button

Control Properties

Each control has properties that determine its appearance and behavior. Here are some common properties:

Common Properties For Most Controls

csharp
// Basic properties
control.Name = "controlName"; // Identifier for the control
control.Text = "Display Text"; // Text displayed on the control
control.Visible = true; // Whether control is visible
control.Enabled = true; // Whether control can be interacted with

// Layout properties
control.Location = new Point(x, y); // Position on parent control
control.Size = new Size(width, height); // Width and height
control.Dock = DockStyle.Top; // How control is docked to parent
control.Anchor = AnchorStyles.Left | AnchorStyles.Top; // How control resizes

// Appearance properties
control.BackColor = Color.White; // Background color
control.ForeColor = Color.Black; // Text color
control.Font = new Font("Arial", 12); // Font for text

Control Events

Events are what make your UI interactive. Here are some common events:

csharp
// Click event - happens when the control is clicked
button.Click += (sender, e) => {
MessageBox.Show("Button was clicked!");
};

// TextChanged event - happens when text is modified
textBox.TextChanged += (sender, e) => {
label.Text = "You typed: " + textBox.Text;
};

// Mouse events
control.MouseEnter += (sender, e) => {
control.BackColor = Color.LightBlue; // Highlight on hover
};

control.MouseLeave += (sender, e) => {
control.BackColor = Color.White; // Return to normal
};

Practical Example: A Temperature Converter App

Let's create a more complete example - a temperature converter application:

csharp
using System;
using System.Windows.Forms;

namespace TemperatureConverter
{
public class ConverterForm : Form
{
private TextBox celsiusTextBox;
private TextBox fahrenheitTextBox;
private Button celsiusToFahrenheitButton;
private Button fahrenheitToCelsiusButton;
private Label resultLabel;

public ConverterForm()
{
this.Text = "Temperature Converter";
this.Size = new System.Drawing.Size(400, 250);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;

InitializeControls();
}

private void InitializeControls()
{
// Labels
var celsiusLabel = new Label
{
Text = "Celsius:",
Location = new System.Drawing.Point(20, 30),
Size = new System.Drawing.Size(80, 20)
};

var fahrenheitLabel = new Label
{
Text = "Fahrenheit:",
Location = new System.Drawing.Point(20, 70),
Size = new System.Drawing.Size(80, 20)
};

// Text boxes
celsiusTextBox = new TextBox
{
Location = new System.Drawing.Point(110, 30),
Size = new System.Drawing.Size(100, 20)
};

fahrenheitTextBox = new TextBox
{
Location = new System.Drawing.Point(110, 70),
Size = new System.Drawing.Size(100, 20)
};

// Buttons
celsiusToFahrenheitButton = new Button
{
Text = "C to F",
Location = new System.Drawing.Point(230, 30),
Size = new System.Drawing.Size(100, 25)
};

fahrenheitToCelsiusButton = new Button
{
Text = "F to C",
Location = new System.Drawing.Point(230, 70),
Size = new System.Drawing.Size(100, 25)
};

// Result label
resultLabel = new Label
{
Text = "Result will appear here",
Location = new System.Drawing.Point(110, 120),
Size = new System.Drawing.Size(200, 20)
};

// Wire up events
celsiusToFahrenheitButton.Click += CelsiusToFahrenheitButton_Click;
fahrenheitToCelsiusButton.Click += FahrenheitToCelsiusButton_Click;

// Add controls to form
this.Controls.Add(celsiusLabel);
this.Controls.Add(fahrenheitLabel);
this.Controls.Add(celsiusTextBox);
this.Controls.Add(fahrenheitTextBox);
this.Controls.Add(celsiusToFahrenheitButton);
this.Controls.Add(fahrenheitToCelsiusButton);
this.Controls.Add(resultLabel);
}

private void CelsiusToFahrenheitButton_Click(object sender, EventArgs e)
{
if (double.TryParse(celsiusTextBox.Text, out double celsius))
{
double fahrenheit = (celsius * 9 / 5) + 32;
fahrenheitTextBox.Text = fahrenheit.ToString("0.##");
resultLabel.Text = $"{celsius}°C = {fahrenheit:0.##}°F";
}
else
{
resultLabel.Text = "Please enter a valid number in Celsius";
}
}

private void FahrenheitToCelsiusButton_Click(object sender, EventArgs e)
{
if (double.TryParse(fahrenheitTextBox.Text, out double fahrenheit))
{
double celsius = (fahrenheit - 32) * 5 / 9;
celsiusTextBox.Text = celsius.ToString("0.##");
resultLabel.Text = $"{fahrenheit}°F = {celsius:0.##}°C";
}
else
{
resultLabel.Text = "Please enter a valid number in Fahrenheit";
}
}

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new ConverterForm());
}
}
}

When you run this code, you'll get an application that lets users convert temperatures between Celsius and Fahrenheit. This example demonstrates:

  1. Creating multiple controls of different types
  2. Organizing them with proper layout
  3. Implementing event handlers for interactivity
  4. Processing and validating user input
  5. Updating the UI based on calculations

WPF Controls

While we've focused on Windows Forms so far, WPF provides an alternative approach to creating UIs with more modern capabilities. Here's a basic example of creating controls in WPF using XAML:

xml
<Window x:Class="WpfControlsDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Controls Demo" Height="350" Width="500">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<!-- Label and TextBox for name -->
<Label Grid.Row="0" Grid.Column="0" Content="Name:" Margin="10,10,5,10"/>
<TextBox Grid.Row="0" Grid.Column="1" Margin="5,10,10,10" Name="nameTextBox"/>

<!-- Label and Slider for age -->
<Label Grid.Row="1" Grid.Column="0" Content="Age:" Margin="10,10,5,10"/>
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal" Margin="5,10,10,10">
<Slider Minimum="0" Maximum="100" Width="200" Name="ageSlider"
ValueChanged="AgeSlider_ValueChanged"/>
<TextBlock Text="{Binding ElementName=ageSlider, Path=Value, StringFormat={}{0:0}}"
Margin="10,0,0,0" VerticalAlignment="Center"/>
</StackPanel>

<!-- Button -->
<Button Grid.Row="2" Grid.Column="1" Content="Submit" Width="100"
HorizontalAlignment="Left" Margin="5,10,10,10" Click="SubmitButton_Click"/>

<!-- Result TextBlock -->
<TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"
Margin="10" Name="resultTextBlock"/>
</Grid>
</Window>

And the corresponding C# code:

csharp
using System;
using System.Windows;
using System.Windows.Controls;

namespace WpfControlsDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void AgeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
// If needed, additional processing when slider value changes
}

private void SubmitButton_Click(object sender, RoutedEventArgs e)
{
string name = nameTextBox.Text;
int age = (int)ageSlider.Value;

if (!string.IsNullOrEmpty(name))
{
resultTextBlock.Text = $"Hello {name}, you are {age} years old!";
}
else
{
resultTextBlock.Text = "Please enter your name.";
}
}
}
}

Advanced Control Concepts

As you progress in your .NET development journey, you'll encounter these more advanced control concepts:

Custom Controls

You can create your own controls by inheriting from existing ones:

csharp
using System.Windows.Forms;
using System.Drawing;

public class ColorfulButton : Button
{
public ColorfulButton()
{
this.FlatStyle = FlatStyle.Flat;
this.FlatAppearance.BorderSize = 0;
this.BackColor = Color.LightBlue;
this.ForeColor = Color.DarkBlue;
this.Font = new Font("Arial", 10, FontStyle.Bold);
}

// You can override painting to create custom visuals
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
// Add custom painting code here
}

// Override mouse events for special effects
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
this.BackColor = Color.SkyBlue;
}

protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
this.BackColor = Color.LightBlue;
}
}

User Controls

For reusable combinations of controls, you can create User Controls:

csharp
using System;
using System.Windows.Forms;

public class AddressEntryControl : UserControl
{
private TextBox streetTextBox;
private TextBox cityTextBox;
private ComboBox stateComboBox;
private TextBox zipTextBox;

public string Street => streetTextBox.Text;
public string City => cityTextBox.Text;
public string State => stateComboBox.Text;
public string ZipCode => zipTextBox.Text;

public AddressEntryControl()
{
InitializeComponents();
}

private void InitializeComponents()
{
// Layout with Labels and TextBoxes for address components
// ... implementation details ...
}

public bool ValidateAddress()
{
// Validation logic
return !string.IsNullOrEmpty(Street) &&
!string.IsNullOrEmpty(City) &&
!string.IsNullOrEmpty(State) &&
!string.IsNullOrEmpty(ZipCode);
}
}

Best Practices for Working with Controls

  1. Naming Convention: Use descriptive names for your controls, such as submitButton instead of button1.

  2. Group Related Controls: Use panels, group boxes, or layout containers to organize related controls.

  3. Validation: Always validate user input before processing it.

  4. Accessibility: Make your UI accessible by providing appropriate tab orders, keyboard shortcuts, and screen reader support.

  5. Responsive Layout: Use docking, anchoring, or layout panels to make your UI adapt to different window sizes.

  6. Consistent Style: Maintain consistent styling across controls for a professional appearance.

  7. Error Handling: Provide clear feedback when errors occur.

Summary

.NET Controls are the essential building blocks for creating interactive user interfaces in desktop applications. In this guide, we've covered:

  • What controls are and their basic purpose
  • Common control types in .NET
  • Working with control properties and events
  • Creating practical applications using Windows Forms
  • Introduction to WPF controls and XAML
  • Advanced concepts like custom controls and user controls
  • Best practices for working with controls

Understanding controls is foundational to becoming proficient in .NET desktop development. As you practice and experiment, you'll gain the confidence to build increasingly complex and user-friendly applications.

Additional Resources and Exercises

Resources

  1. Microsoft Documentation on Windows Forms Controls
  2. WPF Controls Gallery
  3. Microsoft Learn - Create a Windows Forms app

Practice Exercises

  1. Basic Calculator: Create a simple calculator application with buttons for digits and basic operations.

  2. Form Validator: Build a registration form with various controls and implement validation for each field.

  3. Image Viewer: Create an application that lets users browse and view images from their computer.

  4. To-Do List: Build a task management application where users can add, edit, and delete tasks.

  5. Custom Control Challenge: Create a custom progress bar control with a different visual appearance than the standard one.

By working through these exercises, you'll gain practical experience with .NET controls and strengthen your desktop application development skills.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)