TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Control: Windows Forms

Use the Control type in Windows Forms. Cast more derived objects to the Control type.
Control. Windows Forms is built upon an object-oriented type hierarchy. This means that items such as your TextBox and Button are derived from a base class Control. You can act upon these items using the base Control class.
Example. To start, you can create a new Windows Forms application and add several TextBox and Button controls to the enclosing Form by dragging from the Toolbox. Next, add the Form1_Load event by double-clicking on the window itself.

Foreach: This loop acts upon the base.Controls collection. You are accessing each TextBox and Button (among others) in this loop.

Foreach

However: The TextBox and Button instances are being accessed through a reference to their base class.

Casts: You can use the "is" and "as" casts to determine the derived type of the Control reference.

IsAs

Also: You can even mutate the properties of the Control instances by assigning their properties.

C# program that uses Control references 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.OfTypeQuery Windows Forms Controls
Summary. The Control type—and the base.Controls collection on each Form instance—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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf