Control. Windows Forms is built upon an object-oriented type hierarchy. This means that items such as a TextBox and Button are derived from a base class Control.
We can act upon all controls, like TextBox and Button, using the base Control class. This can be useful in some programs, and in loops.
Example. To start, add several TextBox and Button controls to the enclosing Form. Next, add the Form1_Load event by double-clicking on the window itself.
Start This loop acts upon the base.Controls collection. You are accessing each TextBox and Button (among others) in this loop.
However The TextBox and Button instances are being accessed through a reference to their base class.
Tip You can use the "is" and "as" casts to determine the derived type of the Control reference.
Also You can even mutate the properties of the Control instances by assigning their properties.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Loop through each Control in ControlCollection.
foreach (Control control in base.Controls)
{
if (control is TextBox)
{
control.Text = "box";
}
else if (control is Button)
{
control.Text = "push";
}
}
}
}
}
LINQ. You can use the LINQ extensions to the C# language to use the Controls collection. The OfType extension can make searching for all Control instances of a certain derived type easier.
Summary. The Control type lets you access all the items such as TextBox, Button and more in a unified way. This can improve the clarity of your C# code.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.