Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
77
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

To close the application, click the Exit button or the close button on the title bar of the window.

Author's Note: Unfortunately, some builds of Visual Studio.Net do not change the name of the form (from Form1 to MyForm in our case) in the call to the Application.Run() method in the Main() method. You may have to explicitly change the Main() method like this:

static void Main()

{

Application.Run(new MyForm());

}

Make sure to change the name of the form in Main() method whenever you change its name in the Properties Window in order to avoid getting a compilation error.

The code generated by the Form Designer

You can toggle between the Form Designer and Code using View'Designer and View'Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

Using More Controls

Now we are getting familiar with the Visual Studio.Net IDE and its controls, let's learn about some more controls. Note that we will not completely define any control and will demonstrate only some of the more common properties and events. A summary of some of these controls is presented below.

204

Programmers Heaven: C# School

Control

Description

Label

Used to display some text on the form. Instance of System.Windows.Forms.Label. Important

 

properties are Text, Name and Font. Usually events are not handled for the Label control.

Button

Used to display a Push Button on the form. Instance of System.Windows.Forms.Button.

 

Important properties are Text, Name and Font. Usually the Click event is handled for the

 

Button.

TextBox

Provides the user with an area to write/edit text. Instance of System.Windows.Forms.TextBox.

 

Important properties are Text (to set startup text and get what the user has entered), Name,

 

Alignment, Multiline (boolean), ScrollBars (a set of scroll bars attached with the text box),

 

ReadOnly (boolean), WordWrap (boolean) and PasswordChar (character used for password

 

masking). Important events are TextChanged (default) and KeyPress.

GroupBox

Used to group other controls. Instance of System.Windows.Forms.GroupBox. Important

 

properties are Text, Visible (boolean) and Enabled (boolean). Usually events are not handled

 

for the GroupBox.

RadioButton

Allows a user to select one out of many available options. RadioButtons are usually used in a

 

group contained in a GroupBox. Only one of the RadioButton can be selected in a group at a

 

time. Instance of System.Windows.Forms.RadioButton. Important properties are Text, Name

 

and Checked (boolean). Important event is CheckedChanged. Usually the events of a

 

RadioButton are not handled; rather the selected choice is identified on the click of some push

 

button or actions on other controls.

CheckBox

Allows a user to tick or untick a box to state their preference for something. CheckBoxes are

 

usually used in a group contained in a GroupBox. Any, all or none of the checkboxes in a

 

group can be selected. Instance of System.Windows.Forms.CheckBox. Important properties

 

are Text, Name, Checked (boolean) and CheckState. Important events are CheckedChanged

 

and CheckStateChanged.

Using various controls in an application: Programmer's Shopping Cart

Now let's create a 'Programmer's Shopping Cart' application. The Programmer's Shopping Cart is an online bookstore. The best thing about it is that it sells books on both full payment and on installments. The application will finally look like this:

205

Programmers Heaven: C# School

As you can see, we have used the GroupBox (#1), CheckBoxe (#2), RadioButtons (#3), TextBox (#4), Label and Button controls in the above application.

Designing the form and placing the controls

First of all start Visual Studio.Net and create a new Windows Application Project. Set the properties of the form using the Properties Window to the following values:-

Size = 460, 340

StartPosition = CenterScreen

Name = MyForm

Text = Programmer's Shopping Cart

Where StartPosition is the startup position of the form on the screen, Name is the name of form class generated by the designer and Text is the title of the Application's Window.

Now add a Label to the form as shown in the figure above. Set the Text property of the Label to 'Programmer's Shopping Cart'.

Next, from the toolbox window, add a GroupBox to the form. Modify its size appropriately to accommodate three checkboxes and a label. Set the Text property of the GroupBox to 'Available Books' and the Name property to 'gbxAvlblBooks'

From the toolbox window, add three checkboxes to the GroupBox you just made. Set the Text property of the three checkboxes to 'Programming C# ($20)', 'Professional C# ($30)' and 'C# School ($50)'. Also set the Name property of the checkboxes to 'cbxProgCS', 'cbxProfCS' and 'cbxCSSchool'. Add a Label in the GroupBox and set its Text property to 'Select the books you wish to purchase', as shown in the figure.

206

Programmers Heaven: C# School

Add another GroupBox, set its Text property to 'Mode of Payment', its Name property to 'gbxPaymentMode' and its Enabled property to 'False'. Making the Enabled property 'False' will disable the groupbox and all its contents at startup, and it will only be enabled (through coding) when the user has selected some books. Add two RadioButtons in the GroupBox as shown in the figure. Set their Name properties to 'rbnFullPayment' and 'rbnInstallments'. Set the Text property of the radio buttons to 'Full Payment' and 'Installments'. To make the first option (Full Payment) the default option, set its Checked property to True. Add a Label in the GroupBox and set its Text property to 'Select the mode of payment', as shown in the figure.

Add the Purchase button in the form. Set its Name property to 'btnPurchase', its Text property to 'Purchase' and its Enabled property to 'False'. Again the Purchase button will be enabled only when the user has selected some books.

Add a TextBox and a Label to the form. Set the Text property of the Label to 'Comments'. Set the Text property of the TextBox to "" (empty), the Name property to 'txtComments' and the MultiLine property to True. The purpose of setting the MultiLine property to true is to allow the TextBox to have text that spans more than one line. The default value of the MultiLine property is False.

Finally, add an Exit Button to the form. Set its Name property to 'btnExit' and its Text property to 'Exit'.

Writing Code for Event Handling

First of all add an event handler for the Exit Button's Click event by double clicking on it in the designer. Write the following code to exit the application:

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

{

Application.Exit();

}

When the user has selected any book, the 'Mode of Payment' group box and the Purchase button should be enabled, and if all the books are unselected, they should be disabled. This is done by writing an event handler for CheckedChanged event of the checkboxes. To add an event handler for a checkbox, either double click the checkbox in the designer or double click the 'CheckedChanged' event of checkbox in the Event property window. The CheckedChanged event of a checkbox is triggered whenever the checkbox is checked or unchecked or its Checked property is changed. Write the following code in the event handler of first checkbox:

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

{

if(cbxProgCS.Checked == false && cbxProfCS.Checked == false && cbxCSSchool.Checked == false)

{

gbxPaymentMode.Enabled = false;

btnPurchase.Enabled = false;

207

Programmers Heaven: C# School

}

else

{

gbxPaymentMode.Enabled = true;

btnPurchase.Enabled = true;

}

}

In the code above if all the checkboxes are unchecked, we disable the 'Mode of Payment' group box and the Purchase button; otherwise, we enable them.

Copy and paste the same code for the CheckedChanged event of the other two checkboxes (cbxProfCS and cbxCSSchool) Now execute the program and check/uncheck different checkboxes. You will notice if any of the checkboxes are checked, the Mode of Payment group box and Purchase button are enabled, and if none of the checkboxes are checked, they are disabled.

Finally on the Click event of the Purchase Button, the program should display a summary containing a list of books selected, the total cost of the purchase, the mode of payment selected and any comments the user has provided. Add a Click event handler for the Purchase button by double clicking it in the designer and write the following code:

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

{

string message = "You purchased:\r\n\t"; int amount=0;

if(cbxProgCS.Checked)

{

amount+=20;

message+=cbxProgCS.Text + "\r\n\t";

}

if(cbxProfCS.Checked)

{

amount+=30;

message+=cbxProfCS.Text + "\r\n\t";

}

if(cbxCSSchool.Checked)

{

amount+=50;

message+=cbxCSSchool.Text + "\r\n\t";

}

string paymentMode="";

208

Programmers Heaven: C# School

if(rbnFullPayment.Checked)

{

paymentMode = rbnFullPayment.Text;

}

else

{

paymentMode = rbnInstallments.Text;

}

message+="\r\nThe total payment due is $" + amount.ToString(); message+="\r\nThe selected mode of payment is: " + paymentMode;

if(txtComments.Text != "")

{

message+="\r\nYour comments about us are: " + txtComments.Text;

}

MessageBox.Show(message, "Summary");

}

We have used three variables in the above code. The integer variable amount is used to hold the total amount of purchase, the string variable paymentMode is used to hold the selected mode of payment and the string variable message will hold the summary message that will finally be displayed in the MessageBox. First we checked each of the checkboxes and calculated the total amount; at the same time we also build the list of books selected in the string variable message. We then found the mode of payment and concatenated (added) it to the message variable. Next we concatenated the total payment and comments provided to the string variable message. Finally, we displayed the summary message in a Message Box. A message box is a dialog window that pops up with a message. A message box is a modal kind of dialog box, which means when it is displayed you can not access any other window of your application until you have closed the message box. The MessageBox class' static Show method has many overloaded forms; the one we used takes a string to display in the message box and the title of the message box.

Now when we execute the program and press the purchase button after selecting some books, we see the following output:

209

Соседние файлы в папке books