
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdfGeneralized steps to create Windows applications
To create a Windows application, you need to proceed as follows:
1.Select File → New → Project to open the New Project dialog box.
2.In the New Project dialog box, select Visual C# Project in the left pane and select Windows Application in the right pane.
3.Specify a name and path for the new project, if necessary, and click
OK.
Note The Name and the Location boxes in the New Project dialog box contain the default project name and default location. You can change
the entries in the Name and Location boxes to specify a different name and location of the project.
4. The Project window opens. It has a default form in the Design mode. In this mode, you design the form by adding controls to take input and display output. Also, a class called Form1.cs, which is a class for this form, is automatically added to the project. However, you need to add a class to this project, before you can write the code for the class to add the desired functionality to your application.
5.To add a class to the project, select Project → Add Class. The Add New Item dialog box opens.
6.Under Categories, verify that Local Project Items is selected. From the Templates pane, select C# Class. Notice that in the Name box, the
default class name, Class1.cs, appears. Change this default class name to the class name that you want, and then click Open.
7.The code window opens that contains the basic structure of the class.
8.Enter the code in this window to add the desired functionality to your application.
9.Save and build the class.
Before you start creating your own C# Windows application, you first need to understand the C# code that is automatically generated by VS.NET in the Form1.cs class file.
When you open the Form1.cs file, you'll notice that a number of namespaces have been used. Some of the namespaces include System and System.Windows.Forms. The System namespace contains the classes that define commonly used data types, events, event handlers, interfaces, attributes, and processing exceptions. The System.Windows.Forms namespace contains classes that are required for creating Windows Forms.
The Form1.cs file also contains a namespace that has the same name as the name of the Windows application project. Within this namespace, the Form1 class is declared:
public class Form1 : System.Windows.Forms.Form
As you can see in the preceding declaration, Form1 is a class that is derived from the Form class of the System.Windows.Forms namespace.
The Form1 class contains the constructor, which is called automatically when the instance of the Form1 class is created. You can write any initialization code, such as setting a value in a variable or opening a file, in the constructor:
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
//TODO: Add any constructor code after InitializeComponent
//call
//
}
As you can see in the preceding code, the constructor calls another method named InitializeComponent(), which initializes the form and all the components in the form. The code for the InitializeComponent() method is contained within "Windows Forms Designer generated code."
When objects are destroyed (set to Nothing) or are no longer in scope, the .NET Framework automatically calls the Finalize destructor, which is called implicitly and is not included in the code that is automatically generated by VS.NET. However, the only drawback with this destructor is that you do not know when the destructor is called. Also, certain objects might remain active for longer than necessary. To manage your application resources well, VS.NET automatically generates code for the destructor named Dispose. The automatically generated code for the Dispose() method is given as follows:
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
As you can see in the preceding code, the Dispose() method takes a Boolean parameter. If the Boolean parameter is True and the components are not deinitialized, the Dispose() method is called for the components. On the other hand, if the Boolean parameter of the Dispose() method is False, the Dispose() method of the base class is called.
The code that is automatically generated for the Main() method is given as follows:
static void Main()
{
Application.Run(new Form1());
}
As you can see in the preceding code, the object of the Form1 class is passed as an argument to the Run() method of the Application class.
An example to illustrate Windows applications
Now that you know the steps involved in creating a Windows application and the code that is automatically generated by VS.NET, let's create a Windows application that takes the employee code, employee name, and sales made by the employee and calculates and displays the commission earned.
The first step is to create a new project. After creating a new project, design the form, as shown in Figure E-2. Table E-2 lists the Name property of the different text boxes and buttons used in the form.

Figure E-2: A sample Windows form
|
Table E-2: Names of the controls on the sample form |
|
|
|
||
|
|
|
|
|
|
|
|
Control |
|
Contains |
|
Name |
|
|
|
|
|
|
|
|
|
TextBox |
|
Employee |
|
CodeBox |
|
|
|
|
code |
|
|
|
|
|
|
|
|
|
|
|
TextBox |
|
Employee |
|
NameBox |
|
|
|
|
name |
|
|
|
|
|
|
|
|
|
|
|
TextBox |
|
Sales |
|
SalesBox |
|
|
|
|
|
|
|
|
|
TextBox |
|
Commission |
|
CommissionBox |
|
|
|
|
|
|
|
|
|
Button |
|
Calculate |
|
CalculateButton |
|
|
|
|
|
|
|
|
|
Button |
|
Display |
|
DisplayButton |
|
|
|
|
|
|
|
|
Add a class called Employee to this project. Notice that the default constructor appears in the basic code structure. In the code section, add the variables, as follows:
using System;
///Summary description for Employee.
public class Employee
{
private string code;
private string name;
private string sales;
///Default constructor for class Employee public Employee()
{
}
In this code, code, name, and sales are the three private string variables that have been declared.
Now add the properties for the class Employee. For the sample form created in the preceding example, the different employee details include Employee Code, Employee Name, and Sales. You can use these as the properties of the Employee class. To create these properties, you use the get and set accessors. To do so, type the following code in the Employee class (in the Employee.cs file):
///Adding properties to the class Employee
///Adding the EmpName property
public string EmpName
{
get
{
return name;
}
set
{
name=value;
}
}
///Adding the EmpCode property public string EmpCode
{
get
{
return code;
}
set
{
code=value;
}
}
///Adding the EmpSales property public string EmpSales
{
get
{
return sales;
}
set
{
sales=value;
}
}
In the preceding code snippet, the properties named EmpCode, EmpName, and EmpSales have been created, using the get and set accessors.
The next step is to add methods to the Employee class. To add a method that takes sales as a parameter and calculates the commission, type the following code in the Employee class (in the Employee.cs file):
/// Adding a method to calculate the commission
public double Commission(string sales)
{
int z=0;
double CommValue =0;
z=int.Parse(sales);
CommValue=(0.15)*z;
return CommValue;
}
After adding the Commission() method, add the Display() method in the Employee class. The Display() method takes three parameters: strname, strcode, and strsales. Next, this method stores the values, passed as parameters, into a String variable, strdetail. Finally, it returns the value stored in the variable named strdetail.
///Adding a method to display the name, code, and sales public string Display(string strname, string strcode,
string strsal)
{
string strdetail;
strdetail=("Employee Name: "+strname+" Employee Code:
"+strcode+" Sales: "+strsal);
return strdetail;
}
After you've created the Employee class and added properties and methods to this class, the next step is to create the object of the Employee class and use its properties. To do so, switch to the form that you designed earlier. Next, you'll need to associate code with the Click() event of the buttons on the form. First, associate the code to calculate commission with the Click() event of the Calculate button. To do so, double-click the button labeled Calculate. The code window opens automatically. In the code window, the event handler for the Click() event of the button with name CalculateButton is displayed. The code in the CalculateButton_Click() method is given as follows:
private void CalculateButton_Click(object sender, System.EventArgs e)
{
Employee emp1;
emp1= new Employee();
string strsales;
double CommissionValue;
strsales=SalesBox.Text;
CommissionValue=emp1.Commission(strsales);
CommissionBox.Text= CommissionValue.ToString();
}
In the preceding code, an object emp1 of class Employee is created. A string variable, strsales, is used to store the value entered in the text box, SalesBox. This string variable is passed as a parameter to the method Commission(). The method Commission() calculates the commission, which is stored in a variable CommissionValue. Because a text box can only contain strings, you need to convert the value in the double type variable CommissionValue to string. To do this
CommissionValue.ToString() is used.
Next, you'll associate code with the Click() event of the button labeled Display. To do so, double-click the Display button on the form. The event handler for this button is displayed in the code window. The following code is used to call the method Display()
that takes the employee code, name, and sales as parameters and stores them in a variable. A message box that displays these details appears when you click the Display button.
private void DisplayButton_Click(object sender, System.EventArgs e)
{
Employee emp1;
emp1= new Employee();
emp1.EmpName=NameBox.Text;
emp1.EmpCode=CodeBox.Text;
emp1.EmpSales=SalesBox.Text;
string strval;
strval=emp1.Display(emp1.EmpName,emp1.EmpCode,emp1.EmpSales);
MessageBox.Show(strval);
}
After associating code with the Click() event of the buttons labeled Calculate and Display, the last step is to add code in the Main() method of the form, which would act as the entry point of the application. Notice that the basic structure of the Main() method is already defined. You just need to create an object of class Employee and initialize it. To do so, edit the code in the Main() method as follows:
static void Main()
{
Application.Run(new Form1());
Employee emp1;
emp1= new Employee();
}
In this way, you have developed a Windows application that accepts data from the user and performs certain calculations on it. The Display button on the form is used to display the information entered by the user in the form. The Calculate button calculates the commission based on the sales made by the employee.
ASP.NET Web applications
In addition to Visual Basic .NET, you can also use C# to create ASP.NET Web applications. In this section, you'll create an ASP.NET Web application that uses the Employee class that you created in the Windows application. To create an ASP.NET Web application by using C#, follow these steps:
1.Select File → New → Project to open the New Project dialog box.
2.In the New Project dialog box, select Visual C# Project in the left pane and select ASP.NET Web Application in the right pane.
3.In the Name box, specify the name of the application. In the Location box, specify the URL of the computer on which the IIS server is installed.
4.Click OK to create the Visual C# ASP.NET Web application. Solution Explorer displays the list of all the files generated by VS.NET. Currently, WebForm1.aspx file is selected. The VS.NET window displays the WebForm1.aspx file in Design mode.
If you click the Show All Files icon in Solution Explorer and expand the WebForm1.aspx file, you'll notice that the WebForm1.aspx.cs file is also listed under the WebForm1.aspx file. The WebForm1.aspx.cs file is the code behind file that is created by default. When you open this file, you'll notice that a number of namespaces are used. Some of the namespaces include System, System.Web, and System.Web.UI. The System.Web
namespace contains classes that are required for browser/server communication. The System.Web.UI namespace is used to create Web Form pages.
The WebForm1.aspx.cs file automatically declares a namespace whose name is the same as the name of the ASP.NET Web Application project. Within the namespace, the WebForm1 class is declared:
public class WebForm1 : System.Web.UI.Page
As you can see in this declaration, WebForm1 is a class that is derived from the Page class in the System.Web.UI namespace. The WebForm1 class contains the constructor and the Page_Load() and Page_Init() methods. The following is the code for the constructor:
public WebForm1()
{
Page.Init += new System.EventHandler(Page_Init);
}
The constructor associates the Page_Init event handler with the Init event of the Page class, which is generated when the page is requested from the server. In the preceding code, the += operator is used to add the Page_Init event handler to the Init event. This is a powerful feature of C# for associating an event handler with an event at run time based on conditions.
VS.NET generates the following code for the Page_Init event handler:
private void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
//Designer.
//
InitializeComponent();
}
The Page_Init() method calls the InitializeComponent() method, which initializes all the components on the form.
Also, VS.NET declares the Page_Load method that you can use to write any code, such as initializing a variable, which you want to get executed as soon as the page is loaded.
Now that you have a basic understanding of the C# code that is automatically generated by VS.NET, it is time to design the user interface for your application. You design the user interface by placing controls directly on the Web Form. Or, you can design the user interface by switching to the HTML view of the Web Form and writing the ASP.NET code. To design Web Forms, you use Web server controls instead of the Windows
controls. |
|
Note |
When you open the Toolbox, the Web Forms tab lists all the Web |
|
server controls. Notice that the Windows controls are not available |
|
in the Toolbox, because you have created an ASP.NET Web |
|
application and not a Windows application. |
Cross- |
For detailed information on Web Forms technology and |
Reference |
Web server controls, refer to Chapter 3, "Building Forms |
|
with Web Controls." |
For the current ASP.NET Web application, design the Web Form similar to the Windows Form shown in Figure E-2. To do so, use the Label, TextBox, and Button server controls. In Web Forms, the controls have an ID property instead of the Name property (used in Windows Forms). You can use Table E-1 to specify the ID property of the controls on the Web Form. In addition to the existing controls on this form, place one more Label server control and set its ID to DisplayLabel.
After you finish designing the Web Form, you need to associate the programming logic with it, to obtain the desired functionality. To do so, add a class to your project. Because this Web application is intended to implement the same functionality as used for the Windows application, you can add a class that has the same code as in the Employee.cs class file, which you created for the Windows application. Thus, add a new class called Employee.cs and write the following code:
using System;
namespace EmployeeApplication
{
///<summary>
///Summary description for Employee.
///</summary>
public class Employee
{
private string code;
private string name;
private string sales;
public Employee()
{
//
// TODO: Add constructor logic here
//
}
///Adding properties to the class Employee
///Adding the EmpName property
public string EmpName
{
get
{
return name;
}
set
{
name=value;
}
}
/// Adding the EmpCode property
public string EmpCode
{
get
{
return code;
}
set
{
code=value;
}
}
///Adding the EmpSales property public string EmpSales
{
get
{
return sales;
}
set
{
sales=value;
}
}
///Adding a method to the calculate the commission public double Commission(string sales)
{
int z=0;
double CommValue =0; z=int.Parse(sales); CommValue=(0.15)*z; return CommValue;
}
///Adding a method to display the name, code, and sales public string Display(string strname, string strcode, string strsal)
{
string strdetail;
strdetail=("Employee Name: "+strname+" Employee Code: "+
strcode+" Sales: "+strsal);
return strdetail;
}
}
}
Next, you'll need to associate code with the Click() event of the buttons on the Web Form. To do so, first switch to the WebForm1.aspx file in Design mode. Then, to associate code with the Click() event of the button labeled Calculate, double-click this button. The event handler is automatically created for you. Then, write the following code:

private void CalculateButton_Click(object sender, System.EventArgs e)
{
Employee emp1;
emp1= new Employee();
string strsales;
double CommissionValue;
strsales=SalesBox.Text;
CommissionValue=emp1.Commission(strsales);
CommissionBox.Text= CommissionValue.ToString();
}
Also, associate the following code with the button labeled Display:
private void DisplayButton_Click(object sender, System.EventArgs e)
{
Employee emp1;
emp1= new Employee();
emp1.EmpName=NameBox.Text;
emp1.EmpCode=CodeBox.Text;
emp1.EmpSales=SalesBox.Text;
string strval;
strval=emp1.Display(emp1.EmpName,emp1.EmpCode,emp1.EmpSales);
DisplayLabel.Text=strval;
}
When you build and run this application, the output is displayed in a browser. Figure E-3 shows the output when a user enters the employee code, employee name, and sales value, clicks the Calculate button, and then clicks the Display button.
Figure E-3: Output of the ASP.NET Web application