Form Class Code
The figure below shows a straightforward form—based on the class Form1—with a label, a textbox, and two buttons.
The user enters text in the textbox, and clicks one of the buttons to display it in the label. The other button
will be used to hide the form and open an instance of the Form2 class.
To start with, you should get to know the default code for a C# .Net Windows form class.
You can view this code by opening a form in its designer, right-clicking on the designer,
and choosing View Code. Some of the code for the form class is in the hidden Windows Form Designer region, so you won’t see it in the Visual Studio code editor unless you expand this region by clicking the plus icon on the left side of the Code Editor. Let’s have a look
at a few of the pieces of this code.
The statement
public class Form1 : System.Windows.Forms.Form
declares the Form1 class. The colon operator (:) says that it inherits from the .NET Framework class
System.Windows.Forms.Form. (If you’re curious, you can use the Object Browser to inspect the .NEt Framework
Form class.) Everything within the curly braces that follows the class declaration is part of the Form1 class.
Within the Form1 class, you’ll notice another reference to Form1 (mostly empty except for comments):
public Form1()
{
...
}
You can tell that this is the form constructor—it’s where you should put initialization code that you want
executed when an instance of the form is created—because it is a method with the same name as the class.
Further down the form source code module, you’ll find the following code:
static void Main()
{
Application.Run(new Form1());
}
This is the application entry point, and takes a few words of explanation. By default, when you open a
new Windows Application project in C# .NET, the class Form1 is created and added to the project. It’s set
by default to be the startup form, so it needs a Main method to be the entry point, or starting place,
for the compiled application. Within this method, a new object instance of the Form1 class is created using
the new keyword:
Application.Run(new Form1());
Finally, here’s the event code that fills the label with the text supplied by the user when the button is clicked:
private void btnText_Click(object sender, System.EventArgs e) {
label1.Text = txtShow.Text;
}
|