Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft C# Professional Projects - Premier Press.pdf
Скачиваний:
177
Добавлен:
24.05.2014
Размер:
14.65 Mб
Скачать

WINDOWS FORMS AND CONTROLS

Chapter 8

147

 

 

 

FIGURE 8-5 Output of the previous code

Windows Applications

Programmers worldwide have been using different programming languages to create Windows applications that can run locally on a computer. However, all of these languages have their own advantages and limitations. For example, C programmers use the Win32 API (application programming interface) to create Windows applications. On the other hand, Visual Basic provides programmers with a graphical interface to create forms and applications, and Visual C++ uses MFC (Microsoft Foundation Classes) to create Windows applications.

Until now, there was no environment that provided the combined features of these languages. As a result, Microsoft came up with Visual Studio .NET, which provides you with a common framework for developing Windows applications in any of the Visual Studio .NET languages, such as Visual Basic .NET, Visual C++

.NET, and Visual C#. Visual Studio .NET provides a graphical interface for creating applications, and the .NET class library provides you with the classes you can use to write the code for your application.There’s no doubt that you can create Windows applications easily and in far less time by using the .NET Framework. The next section will look at creating a Windows application.

Creating a Windows Application

To create a Windows application, select the Windows Application project template in the Templates pane of the New Project dialog box. In the Name text box, specify a name for your application, SampleWindowsApplication, and in the Location text box, type the path or browse to the directory in which you want to save your application.

148 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

After you create a Windows application with the name SampleWindowsApplication, Visual Studio .NET creates a solution and a project with the same name. The Windows application opens in the Windows Forms Design view. A default form, Form1, is created for you in the design view. Form1 is an instance of the Form class of the .NET class library and is an interface for your application.

 

 

 

 

 

 

TIP

 

 

Y

 

 

 

 

 

 

 

 

 

 

 

 

L

 

The Form class lies in the System.Windows.Forms namespace.

 

 

 

F

 

 

 

M

 

 

 

 

A

 

 

 

In addition to creating a default form, Visual Studio .NET creates the default files

 

and references that you require to create your project. Table 8-1 lists some of these

 

files.

E

 

 

 

 

T

 

 

 

 

Table 8-1 The Windows Application Files

 

 

 

Files

Description

 

 

 

 

 

 

 

AssemblyInfo.cs

The AssemblyInfo.cs file contains assembly information,such as the

 

 

versions of the assembly.

 

 

 

Form.cs

The Form.cs file contains the code for the default form.

 

References

The References folder includes references to the namespaces that you

 

 

use for the de velopment of an application. For example, the References

folder contains System, System.Data, System.Drawing, System.Windows.Forms, and System.XML files that contain references to the respective namespaces.

Figure 8-6 displays the default files that are included in the SampleWindowsApplication project.

Team-Fly®

WINDOWS FORMS AND CONTROLS

Chapter 8

149

 

 

 

FIGURE 8-6 Windows application files

Visual Studio .NET also creates the code for the default form, Form1, which is created in the Windows application. To view the code behind the form, you can either double-click on the form or select the form and press the F7 key. The following sample shows the code that is automatically generated when you create a Windows application.

using System;

using System.Drawing; using System.Collections;

using System.ComponentModel; using System.Windows.Forms; using System.Data;

namespace SampleWindowsApplication

{

public class Form1 : System.Windows.Forms.Form

{

private System.ComponentModel.Container components = null; public Form1()

{

InitializeComponent();

}

150 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code private void InitializeComponent()

{

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); this.Name = “Form1”;

this.Text = “Form1”;

this.Load += new System.EventHandler(this.Form1_Load);

}

#endregion

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private void Form1_Load(object sender, System.EventArgs e)

{

--------

}

}

}

When you create a Windows application in Visual Studio .NET, a default namespace with the same name as that of your application is also created. In this case,

WINDOWS FORMS AND CONTROLS

Chapter 8

151

 

 

 

a default namespace is created with the name SampleWindowsApplication. In addition, Visual Studio .NET includes some of the existing namespaces in the appli-

cation, such as System, System.Drawing, System.Collections, and so on. Inside the

SampleWindowsApplication namespace, a public class named Form1 is created. When you add controls to the form, the declarations of the controls are added to this class. You will learn to add controls to a form later in this chapter.

The Form1 class contains a default constructor named Form1. The constructor includes the InitializeComponent() method. This method contains the statements required to initialize the Windows form used in the application. For example, the InitializeComponent() method includes the name of the form. The declaration for the InitializeComponent() method is included in the #region preprocessor directive.

TIP

#region preprocessor directives are used to demarcate regions.

In addition, the Form1 class contains the Dispose() method, which is called to deallocate the memory occupied by the components that are no longer used by the application.The class also includes the Main() method, which is the starting point of the execution of the program. Finally, the public class includes the declaration of the Form1_Load method, which is used in the InitializeComponent() method.

This previous code creates a blank form for your application to which you need to add functionality through various controls.The following section discusses how to add controls to your form.

Adding Controls to a Windows Form

Visual Studio .NET provides you with various Windows form controls that you can add to your application by just dragging the controls to your form. Figure 8-7 displays the Windows form controls available with Visual Studio .NET.

152 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

FIGURE 8-7 Windows form controls available with Visual Studio .NET

You will now add a button to SampleWindowsApplication. To add a button, drag a Button control to the form. You can place the Button control anywhere in the form. Figure 8-8 shows a Windows form with a Button control.

FIGURE 8-8 Windows form with a Button control

WINDOWS FORMS AND CONTROLS

Chapter 8

153

 

 

 

As discussed earlier, when you add a control to the form, the declaration of the control is added to the Form1 class. The following code shows the declaration of the Button control:

private System.Windows.Forms.Button button1;

As you can see, the button has the text button1 on it. To change the text displayed on the button, you must change its properties.

Changing the Properties of a Windows Form Control

You can view the properties of a button in the Properties window. Figure 8-9 displays the Properties window.

FIGURE 8-9 The Properties window

To change the properties of the button, perform the following steps:

1.Select the button to make it active.

2.In the Properties window, make the following changes to the properties of a button:

Text: Welcome

Name: sampleButton

154 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

Font:

Name: Arial

Your button now displays the text Welcome. The button that you created, however, does not perform any action. To add some functionality to the button, you need to add code to button1_Click() method. You can add code to display a message box when the button is clicked.

private void button1_Click(object sender, System.EventArgs e)

{

MessageBox.Show(“This is a sample Windows Application”);

}

The sample Windows application that you created in the preceding code is shown in Figure 8-10.

FIGURE 8-10 Sample Windows application

In addition to the Button control, you can create other controls in a Windows application.The following section discusses some of these controls.

WINDOWS FORMS AND CONTROLS

Chapter 8

155

 

 

 

Types of Windows Forms Controls

Windows forms controls are used with Windows forms to accept user input. In addition to using Windows controls that are provided by Visual Studio .NET, you can create custom controls. In this section, you will look at some of the controls provided by Visual Studio .NET.

Button Control

A Button control is used to allow a user to perform a specified action on the click of a mouse. You can specify the action to be performed in the click event of the button. The following steps will create a Button control in a Windows form, Form1, which displays another form, Form2, when the button is clicked. In addition, Form1 is hidden when the button is pressed. To create the Button control, perform the following steps:

1.Drag a Button control from the Windows Forms toolbox to Form1.

2.Change the following properties of the Button control:

Name: btnShow

Text: &Show

3.Double-click on the Button control to display the code.

4.Add the following code to the Click event of the control:

private void button1_Click(object sender, System.EventArgs e)

{

Form2 newForm = new Form2(); newForm.Show();

this.Hide();

}

TIP

If you prefix a letter in the Text property of a Button control with an ampersand (&), Visual Studio .NET creates the letter as the access key for the Button control. You can then access the button by using the Alt key in combination with the access key. For example, prefixing an ampersand with the letter S in the text property of the Show button allows you to click the Show button by using Alt and S keys.

156 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

Label Control

A Label control is used to display static text or images. You can use a Label control to display the descriptions of controls used in a form. For example, you can create a Label control to specify the description of the Button control that you created in the previous example. To create the Label control, perform the following steps:

1.Drag a Label control from the Windows Forms toolbox to Form1.

2.Change the following properties of the Label control.

Name: lblDescription

Text: Click on the Show button to display Form 2

Font:

Name: Arial

Size: 10

Bold: True

Figure 8-11 shows Form1.

FIGURE 8-11 Form1

WINDOWS FORMS AND CONTROLS

Chapter 8

157

 

 

 

TextBox Control

A TextBox control is used to allow a user to input values to a form. You can also use a TextBox control to display dynamic text. This implies that you can change the value in the text box at run time.

MainMenu Control

A MainMenu control is used to create menu items in a form. You can drag the MainMenu control to the form to create menu items at run time. You can use the Checked property of the MainMenu control to find whether the control is selected or not. The following steps show you how to create the File menu for Form1.

1.Drag a MainMenu control from the Windows Forms toolbox to the form.

A menu item is added to the form.

2.Click on the text Type Here and type the name of the first menu item as

&File.

3.In the text area below the File menu, type &New to create the New option.

Similarly, you can create the Open, Save, Save As, and Exit options.

4.To add a menu item adjacent to the File option, type &Edit in the text area to the right of the File menu.

Similarly, you can create Cut, Copy, and Paste options on the Edit menu.

However, the menu items that you have created so far do not perform any function. To add functionality to the menu item, you need to add code to the click event of the menu option.

5.Double-click the New option to display the code window.

6.Type the following code in the click event of the New option.

private void menuItem2_Click_1(object sender, System.EventArgs e)

{

Form2 newForm = new Form2(); newForm.Show();

this.Hide();

}

158 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

When you click the New option on the File menu, a new form, Form2, is created for you. Similarly, you can write code for other options. Figure 8-12 displays the New option.

 

 

Y

 

L

 

F

 

M

 

A

 

E

 

T

 

 

FIGURE 8-12 The New option

GroupBox Control

A GroupBox control is used to create a group of controls, such as RadioButton, CheckBox, TextBox controls, and so on. You can give a specific name to a GroupBox control that can be used to identify each item in the GroupBox control.

RadioButton Control

A RadioButton control is used to allow users to select an option from a group of two or more options. You can use a GroupBox control to group RadioButton controls. In the previous example of a Button control, when a user clicks the button, Form2 is displayed. However, in this case, if the user has the option of viewing more than one form, you can create a group of RadioButton controls. To do this, perform the following steps:

Team-Fly®

WINDOWS FORMS AND CONTROLS

Chapter 8

 

159

 

 

 

 

 

1.Drag a GroupBox control to the form.

2.Change the Text property of the GroupBox control to Forms.

3.Drag three RadioButton controls and place them within the GroupBox control.

4.In the Properties window, change the following properties of the RadioButton controls:

RadioButton1:

Name: btnForm1

Text: Form1

RadioButton2:

Name: btnForm2

Text: Form2

RadioButton3:

Name: btnForm3

Text: Form3

To make the radio buttons functional, write the code for the click events of the RadioButton controls.

1.Double-click on btnForm1 to open the code window.

2.Add the following code to the click event of btnForm1.

private void btnForm1_CheckedChanged(object sender, System.EventArgs e)

{

Form1 newForm = new Form1(); newForm.Show();

this.Hide();

}

The previous code creates an instance of Form1.The instance of Form1 is used to call the Show() method to display Form1. The this.Hide() statement is used to hide the current form.

Similarly, you can write the code for btnForm2 and btnForm3.

1. Double-click on btnForm2 to open the code window.

160 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

2. Add the following code to the click event of btnForm2.

private void btnForm2_CheckedChanged(object sender, System.EventArgs e)

{

Form2 newForm = new Form2(); newForm.Show();

this.Hide();

}

3.Double-click on btnForm3 to open the code window.

4.Add the following code to the click event of btnForm3:

private void btnForm3_CheckedChanged(object sender, System.EventArgs e)

{

Form3 newForm = new Form3(); newForm.Show();

this.Hide();

}

5. Save the form by using the Save option on the File menu.

Figure 8-13 shows the GroupBox control with the three radio buttons.

FIGURE 8-13 RadioButton controls

WINDOWS FORMS AND CONTROLS

Chapter 8

 

161

 

 

 

 

 

CheckBox Control

A CheckBox control allows a user to select a state, which can be either True or False. A CheckBox control is similar to a RadioButton control; however, you can create a group of CheckBox controls that allow user to select more than one value. To select an option, a user needs to check the CheckBox control.

To determine whether a CheckBox control is selected or not, you can use the Checked property, which returns a Boolean value, True or False, depending on whether the user has selected the check box or not.

To make a CheckBox control functional, you need to add code to the control. You can use the CheckState property of the CheckBox control to specify the action to be performed, depending on whether the control is checked or not. The CheckState property returns a value of Checked or Unchecked.

ListBox Control

A ListBox control is used to allow users to select one or more options from a list of items. You can use the SelectionMode property to specify whether a user can select one or multiple options. For example, if you set the SelectionMode property to one, the user can select only one option. However, if the SelectionMode property is set to either MultiSimple or MultiExtended, the user can select multiple options.

To create a ListBox control that allow users to select only one option, perform the following steps:

1.Drag a ListBox control to the form.

2.In the Properties window, set the following properties of the control:

Name: listBox1

SelectionMode: One

The ListBox control is empty until now. To add values to the control, perform the following steps:

3.In the Properties window, select the Items property by clicking on the ellipsis button.

The String Collection Editor window is displayed.

162Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

4.Add values to the String Collection Editor window by typing each value in a single row.

You can add values such as OptionA, OptionB, OptionC, OptionD, and

OptionE.

5.Click on the OK button to close the String Collection Editor window.

6.Click on the Save option on the File menu to save the form.

The values are displayed in the ListBox control. You can now resize the control according to your need. If the options require more space than that provided, a scroll bar appears. Figure 8-14 shows the ListBox control with values added to it.

FIGURE 8-14 ListBox control

ComboBox Control

A ComboBox control allows users to select an option from a list of options. In addition, you can type an option in the ComboBox control if you do not want to select any of the available options.

WINDOWS FORMS AND CONTROLS

Chapter 8

163

 

 

 

To determine the option that a user selects, you can use the SelectedIndex property. The SelectedIndex property returns the index value of the item that is selected. However, if you do not select any option, the value returned by the SelectedIndex property is -1.

NOTE

Both the ListBox and ComboBox controls are used to allow users to select an option from the items list. However, a ListBox control does not allow a user to enter values. This implies that a user is restricted to selecting an option from the available list.

Alternatively, a ComboBox control provides the user with suggested options. The user may or may not select the options that are provided in the ComboBox control.

MonthCalendar Control

A MonthCalendar control allows users to select a date from a calendar that displays dates and months. By default, the current date is selected. However, a user is allowed to select any other date by clicking on the date value. The user can also change the month by clicking on the arrow buttons that appear at the top of the MonthCalendar control. A MonthCalendar control allows you to select multiple dates. The control also allows you to specify a range of dates that you can select.

DateTimePicker Control

A DateTimePicker control is used to allow users to select a single date from the calendar of dates that is displayed when a user clicks the Down Arrow button. A user can also type the date in the text box area of the DateTimePicker control. Unlike the MonthCalendar control, you can also specify the time in the DateTimePicker control.

When the user clicks the Down Arrow button, a MonthCalendar control is displayed, which allows you to select a date by clicking on the date in the MonthCalendar control.

Figure 8-15 shows a MonthCalendar control and a DateTimePicker control.