Home

Introduction to Text-Based Controls

 

Introduction to Labels

 

Description

A label is a control that serves as a guide to the user. It provides static text that the user cannot change but can read to get information on a form. The programmer can also use it to display simple information to the user. Most controls on the form are not explicit at first glance and the user may not know what they are used for. Therefore, you can assign a label to a control as a help to the user.

 

Creating a Label

To add a label to a container, click the Label button Label from the Toolbox and click the object that would host it.

To programmatically create a label, declare a handle to Label, initialize it using its default constructor, and add it to the Controls property of the form. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    Label lblMessage;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lblMessage = new Label();
        Controls.Add(lblMessage);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

Practical LearningPractical Learning: Introducing Labels

  1. Start Microsoft Visual C# and create a Windows Application named ElementaryAddition1
  2. From the Common Control section of the Toolbox, click Label and click the form
  3. From the Common Control section of the Toolbox, click the Label again and click the form
  4. From the Common Control section of the Toolbox, click the Label again and click the form

Characteristics of a Label

 

The Caption

The most important characteristic of a label control is the text it displays. That text is also referred to as its caption and this is what the user would read. The text of a label is its Text property and is its default. To set a labelís caption, after adding the control to a container, click Text in the Properties window and type the desired value. As we mentioned when studying controls characteristics, at design time, the text you type in the Text field is considered ďas isĒ. If you want to create a more elaborate and formatted string, you would have to do it programmatically. Here is an example:

public class Exercise : System.Windows.Forms.Form
{
    Label lblMessage;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lblMessage = new Label();
        lblMessage.Text = DateTime.Now.ToString();
        Controls.Add(lblMessage);
    }
}

Here is an example of what this would produce:

Label's Caption

When it comes to its caption, one of the most valuable characteristics of the text of a label is the variance of the font. When designing a caption. you can change the default font to make it more attractive.

Practical LearningPractical Learning: Captioning the Labels

  1. On the form, click the first label
  2. In the Properties window, click Text and type 00
  3. Click (Name) and type lblOperand1
  4. Click TextAlign and the arrow of its combo box to select Center
  5. Click the + button of the Font field and change the characteristics as follows:
    Name: Tahoma
    Size:   48
    Bold:   True
  6. On the form, click the second label and, in the Properties window, change its characteristics as follows:
    Text: +
    TextAlign: Center
    (Name): lblOPeration
    Font -> Name: Arial
    Font -> Size:   50
    Font -> Bold:   True
  7. On the form, click the third label and, in the Properties window, change its characteristics as follows:
    Text: 00
    TextAlign: Center
    (Name): lblOperand2
    Font -> Name: Arial
    Font -> Size:   50
    Font -> Bold:   True
  8. Save all

Automatically Sizing a Label

After adding a label to a form, by default, it receives a fixed size. If you type its caption and press Enter, the text you provided would be confined to the allocated dimensions of the control. If the text is too long, part of it may disappear. You can then resize the label to provide more area. Another solution is to automatically resize the label to accommodate the length of the string you typed. This is aspects is controlled by the Boolean AutoSize property. Its default value is False. If you set this property to True, at design time, a rectangular border appears around it. If you type a string in the Text field and press Enter, the control would be resized to show the whole string but using only the necessary space.

If you programmatically create a label, it assumes a default size. If you assign it a string that is too long for that default size, part of the string may appear on a subsequent line. If you want the whole string to appear on the same line, you can set the AutoSize to true. Here is an example:

public class Exercise : System.Windows.Forms.Form
{
    Label lblMessage;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lblMessage = new Label();
        lblMessage.Text = DateTime.Now.ToString();
        lblMessage.AutoSize = true;
        Controls.Add(lblMessage);
    }
}

Here is an example of what this would produce:

Label Auto Size

Practical LearningPractical Learning: Using AutoSize

  1. Click an unoccupied area of the form and press Ctrl + A to select all three labels
  2. In the Properties window, double-click AutoSize to set the value to False
  3. Save all

Content Alignment

After typing the caption of a label whose AutoSize property is set to False, you can resize its allocated space to your liking. This is because a string occupies a rectangular area. Here is an example:

Content Alignment

By default, the caption of a label is positioned starting on the middle-left side of its allocated rectangle. Alternatively, you can position it to one of the nine available positions. As we saw is Lesson 5, the position of the caption of a label is controlled by the TextAlign property which is based on the ContentAlignment enumerator:

Text Alignment

It can have the following values:

TopLeft TopCenter TopRight
TopLeft TopCenter TopRight
MiddleLeft MiddleCenter MiddleRight
MiddleLeft MiddleCenter MiddleRight
BottomLeft BottomCenter BottomRight
BottomLeft BottomCenter BottomRight

Pictures on a Label

Other fancy characteristics you can apply to a label include its font and color. For example, a label is primarily meant to display a string. To make it fancier, you can display a (small) picture next to it. To do this, at design time, use the Image field of the Properties window to select a picture. You can also specify the picture at run time by assigning an Image value to the Label.Image property. After adding a picture that would accompany the label, you can specify what position the picture would hold with regards to the label. To do this, select the desired position of the ImageAlign field in the Properties window.

Instead of using a picture from the Image property, you can create a list of images using an ImageList control and assign it to the label. In fact, the advantage of an ImageList is that, unlike the Image property, it allows you to use more than one picture.

After assigning an ImageList to the label control using the Properties window or code, you can use the ImageIndex to specify what picture to display next to the label.

A Label's Mnemonic

A label provides another property called UseMnemonic. This property is valuable only when the label accompanies another control.

Practical LearningPractical Learning: Using a Text Box

  1. Complete the design of the form as follows:
     
    Elementary
    Control Text Name TextAlign Font Additional Properties
    Label 00 lblOperand1 Center Name: Tahoma
    Size:   48
    Bold:   True
    ForeColor: Blue
    Label +   Center Name: Arial
    Size:   50
    Bold:   True
    ForeColor: Maroon
    Label 00 lblOperand2 Center Name: Tahoma
    Size:   48
    Bold:   True
    ForeColor: Blue
    Label =   Center Name: Arial
    Size:   50
    Bold:   True
    ForeColor: Green
    Label 00 lblResult Center Name: Tahoma
    Size:   48
    Bold:   True
     
    Label New Operation lblNewOperation Center Name: Tahoma, Size: 28 Bold: True BorderStyle: Fixed3D
    ForeColor: White
    BackColor:Maroon 
    Label Quit lblQuit Center Name: Tahoma, Size: 28 Bold: True BorderStyle: FixedSingle
  2. To be able to use the Visual Basic library, in the Solution Explorer, right-click References -> Add References...
  3. In the .NET property page, click Microsoft.VisualBasic
     
  4. Click OK and OK
  5. Double-click New Operation and implement its event as follows:
     
    private void lblNewOperation_Click(object sender, EventArgs e)
    {
            int operand1;
            int operand2;
            int answer = 0;
    
            Random rnd = new Random();
    
            operand1 = rnd.Next(99);
            operand2 = rnd.Next(99);
            int result = operand1 + operand2;
    
            lblOperand1.Text = operand1.ToString();
            lblOperand2.Text = operand2.ToString();
            lblResult.Text = "0";
            string strPrompt = lblOperand1.Text + " + " +
                                   lblOperand2.Text + " =";
    
            try
            {
                    answer =
    	           int.Parse(Microsoft.VisualBasic.Interaction.InputBox(
                               strPrompt,
                               "Elementary Addition",
                               "000",
                               100,
                               100));
    
            	lblResult.Text = answer.ToString();
    
            	if (answer == result)
                            MessageBox.Show("WOW - Good Answer");
            	else
                            MessageBox.Show("PSSST - Wrong Answer");
            }
            catch (FormatException)
            {
            }
    }
  6. Return to the form and double-click Quit
  7. Implement its event as follows:
     
    private void lblQuit_Click(object sender, EventArgs e)
    {
                Close();
    }
  8. Execute the application and test it
     
    Elementary
     
     
     
     
  9. Click the Close button to close the form and return to your programming environment

Link Labels

 

Introduction

In the past, to add an internet or email link to a form, there were many steps to follow. As the internet and email had become an integral part of the culture, it was also time to have an appropriate control adapted for this need. To address this issue, a control called LinkLabel is available from the .NET Framework.

Characteristics of the Link Label

As its name indicates, the LinkLabel control allows you to create a link. If you have done web development, you would know that a link can be made fancy by varying its colors. A link typically uses three different colors (actually, if you use cascading style sheet, you can add a fourth color as hover):

  • Link: This is the general color used on a link that a user has not clicked before. The LinkLabel class defines this color through the LinkColor property.
  • Active Link: When the user clicks a link, its target typically opens if everything is alright. This causes the link to change its color status. The color of an active link is represented in the LinkLabel class with the ActiveLinkColor property.
  • Visited: When a user comes to a page or the document that provides a link, you can indicate whether the link was previously accessed or not. This is done by displaying a color other than the link color. The color of a previously visited link is represented in the LinkLabel class by the VisitedLinkColor property.

After creating a link, when the user accesses it, you can define some behavior the link would exhibit to the user, such as getting underlined or not underlined when the mouse passes over the link. The behaviors of a link can be controlled through the LinkBehavior property whose values are AlwaysUnderline, HoverUnderline, NeverUnderline, or the application would refer to Internet Options dialog box of Control Panel.

A link is typically meant to help the user switch to a different page or document when clicked. In some cases and at a particular time, you may not want the user to be able to click a link. In this case you can disable it. If you decide to disable a link, you can change its color using the DisabledLinkColor property. On the other hand, if the user is not able to access a link, that is, if a link is disabled, you can find out the color of that link from the DisabledLinkColor property.

Here is an example:

private void linkLabel1_LinkClicked(object sender,
            LinkLabelLinkClickedEventArgs e)
{
        System.Diagnostics.Process.Start(
    		@"C:\Program Files\Internet Explorer\iexplore.exe",
        		"http://www.functionx.com/vccli");
}

Introduction to Text Boxes

 

Introduction

A text box is a Windows control used to get or display text to the user. At its most regular use, a text box serves as a placeholder to fill out and provide information. Such a use is common on employment applications, login dialog boxes, forms, etc. Like most other controls, the role of a text box is not obvious at first glance; that is why it should be accompanied by a label that defines its purpose.

From the userís standpoint, a text box is named after the label closest to it. Such a label is usually positioned to the left or the top side of the text box. From the programmerís point of view, a text box is a placeholder used for various things. For example, you can show or hide it as you see fit. You can also use it only to display text without allowing the user to change it.

Creating a Text Box

To create a text box, from the Common Controls section of the Toolbox, you can click TextBox Text Box and click the form. The text box is based on the TextBox class. This means that you can use this class to dynamically create a text box and add it to your application. The text box control is based on the TextBox class whose immediate parent is TextBoxBase. Like every .NET Framework class, it has a constructor that can be used to dynamically create the control. The TextBoxBase class provides other methods derived from the controlís parent or from ancestor classes.

Using the Text of a Text Box

 

Introduction

As a control primarily meant to display text, like a label, the text box shares many of the characteristics of a label: text alignment, font, color, etc.

The most important aspect of a text box is its text, whether it is displaying or requesting it. This is the Text property. When you add a text box control to a form or other container, by default, it is left empty. If you want the control to display some text when the form launches, type a string in the Text property field in the Properties window.

After creating a text box, it may be empty, the user can start typing in it to fill it with text. You can programmatically assign it a string to occupy it. Another way you can put or add text to the control is to paste the content of the clipboard, using text from another control. The syntax of the Paste() method is:

public void Paste();

At any time, to know the length of the text in the control, you can retrieve the value of the TextLength property, which is of type int.

Selecting Text

The selection of text from a text box control can be performed either by you or by a user. To select part of the text, you can specify the starting point using the SelectionStart property, which is of type int. After the starting position, you can specify the number of characters to include in the selection. This is done using the SelectionLength property, which is of type int. The SelectionStart and the SelectionLength properties allow you to programmatically select text. The user, on the other hand, also knows how to select part of the text of the control. These operations can also be performed using the Select() method of the TextBox class. Its syntax is:

public void Select(int start, int length);

Alternatively, the user may want to select the whole content of the control. To programmatically select the whole text of a text box control, call the SelectAll() method. Its syntax is:

public void SelectAll();

When  some text has been selected in the control, to get that text, you can retrieve the value of the SelectedText property, which is a handle to String.

Operations on Text

After the text, in part or in whole, has been selected, you or the user can manipulate it. For example, you can copy the selection to the clipboard. This is done using the Copy() method. Its syntax is:

public void Copy();

To delete part of the text, the user can cut it. You can programmatically do this using the Cut() method. Its syntax is:

public void Cut();

To delete the whole contents of the text box, you can call the Clear() method. Its syntax is:

public void Clear();

Any operation performed on the text box can be undone using the Undo() method whose syntax is:

public void Undo();

To prevent an undo operation, call the ClearUndo() method. Its syntax is:

public void ClearUndo();

Practical LearningPractical Learning: Introducing Text Boxes

  1. Create a Window Forms Application named ElementaryAddition2
  2. Design the form as follows:
     
    Elementary Addition
    Control Text Name TextAlign Font Additional Properties
    Label 00 lblOperand1 Center Name: Tahoma
    Size:   48
    Bold:   True
    AutoSize: True
    ForeColor: Blue
    Label +   Center Name: Arial
    Size:   50
    Bold:   True
    AutoSize: True
    ForeColor: Maroon
    Label 00 lblOperand2 Center Name: Tahoma
    Size:   48
    Bold:   True
    AutoSize: True
    ForeColor: Blue
    Label =   Center Name: Arial
    Size:   50
    Bold:   True
    AutoSize: True
    ForeColor: Green
    TextBox 000 txtResult Center Name: Tahoma
    Size:   48
    Bold:   True
     
    Label New Operation lblNewOperation Center Name: Tahoma, Size: 28 Bold: True AutoSize: True
    BorderStyle: Fixed3D
    ForeColor: White
    BackColor:Maroon 
    Label Check lblCheckAnswer Center Name: Tahoma, Size: 28 Bold: True AutoSize: True
    BorderStyle: Fixed3D
    ForeColor: White
    BackColor:Maroon 
    Label Quit lblQuit Center Name: Tahoma, Size: 28 Bold: True AutoSize: True
    BorderStyle: FixedSingle
  3. Double-click the New Operation label and implement its event as follows:
     
    private void lblNewOperation_Click(object sender, EventArgs e)
    {
            int operand1;
            int operand2;
    
            Random rnd = new Random();
    
            operand1 = rnd.Next(99);
            operand2 = rnd.Next(99);
            int result = operand1 + operand2;
    
            lblOperand1.Text = operand1.ToString();
            lblOperand2.Text = operand2.ToString();
            txtResult.Text   = "";
            txtResult.Focus();
    }
  4. Return to the form and double-click the Check label
  5. Implement its event as follows:
     
    private void lblCheckAnswer_Click(object sender, EventArgs e)
    {
            int Operand1 = 0;
            int Operand2 = 0;
            int Result = 0;
    
            try
            {
                    Operand1 = int.Parse(lblOperand1.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    Operand2 = int.Parse(lblOperand2.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    Result = int.Parse(txtResult.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Answer");
            }
    
            if (Result == (Operand1 + Operand2))
                    MessageBox.Show("WOW - Good Answer");
            else
                    MessageBox.Show("PSSST - Wrong Answer");
    
            lblNewOperation_Click(sender, e);
    }
  6. Return to the form and double-click Quit
  7. Implement its event as follows:
     
    private void lblQuit_Click(object sender, EventArgs e)
    {
                Close();
    }
  8. Execute the application and test it
  9. Click the Close button to close the form and return to your programming environment

Characteristics of Text Boxes

 

Mnemonics

As mentioned already, a text box should be accompanied by a label that indicates what it is used for. To support this relationship, the Label control provides various properties. An accelerator character is a symbol of the label that provides easy access to its text box. On the label, such a character is underlined. An example would be First Name. The idea is that, if the user presses the Alt key in combination with the labelís underlined character, the text box it accompanies would receive focus.

To create an accelerator key, choose one of the labelís characters and precede it with an ampersand character when setting its caption. An example would be &First Name. If you want a label to display the accelerator character instead of a plain ampersand, set the labelís UseMnemonic property to true, which is already its default value. If you set it to true but need to display an ampersand, type two & characters where the ampersand would be shown.

The UseMnemonic property of a label is only used to indicate that the label would display an accelerator character and the & symbol typed on the label creates that accelerator character. To indicate which text box would receive focus when the accelerator character of the label is invoked, you must make sure you establish an appropriate tab sequence using the Tab Order menu item from the main menu or using the combination of TabStop/TabIndex properties. Typically, the label should have a Tab Order or TabIndex value that is just - 1 of that of the control it serves.

Practical LearningPractical Learning: Creating Text Boxes

  1. To start a new application, on the main menu, click File -> New -> Project (or File -> New Project)
  2. In the Templates list, click Windows Application and set the name to PayrollProcessing1
  3. Click OK
  4. Design the form as follows:
     
    Payroll Processing
    Control Name Text Other Properties
    GroupBox GroupBox   Employee Identification  
    Label Label   &Employee Name:  
    TextBox TextBox txtEmployeeName    
    Label Label   Hourly &Salary:  
    TextBox TextBox txtHourlySalary    
    GroupBox GroupBox   Time Values  
    Label Label   Monday  
    Label Label   Tuesday  
    Label Label   Wednesday  
    Label Label   Thursday  
    Label Label   Friday  
    Label Label   Saturday  
    Label Label   Sunday  
    Label Label   First Week:  
    TextBox TextBox txtMonday1 0.00 TextAlign: Right
    TextBox TextBox txtTuesday1 0.00 TextAlign: Right
    TextBox TextBox txtWednesday1 0.00 TextAlign: Right
    TextBox TextBox txtThursday1 0.00 TextAlign: Right
    TextBox TextBox txtFriday1 0.00 TextAlign: Right
    TextBox TextBox txtSaturday1 0.00 TextAlign: Right
    TextBox TextBox txtSunday1 0.00 TextAlign: Right
    Label Label   Second Week:  
    TextBox TextBox txtMonday2 0.00 TextAlign: Right
    TextBox TextBox txtTuesday2 0.00 TextAlign: Right
    TextBox TextBox txtWednesday2 0.00 TextAlign: Right
    TextBox TextBox txtThursday2 0.00 TextAlign: Right
    TextBox TextBox txtFriday2 0.00 TextAlign: Right
    TextBox TextBox txtSaturday2 0.00 TextAlign: Right
    TextBox TextBox txtSunday2 0.00 TextAlign: Right
    GroupBox GroupBox   Payroll Processing  
    Label Label   Hours  
    Label Label   Amount  
    Button Button btnCalculate Calculate  
    Label Label   Regular  
    TextBox TextBox txtRegularTime 0.00 TextAlign: Right
    TextBox TextBox txtRegularAmount 0.00 TextAlign: Right
    Label Label   Net Pay:  
    TextBox TextBox txtNetPay 0.00 TextAlign: Right
    Label Label   Overtime  
    TextBox TextBox txtOvertime 0.00 TextAlign: Right
    TextBox TextBox txtOvertimeAmount 0.00 TextAlign: Right
    Button Button btnClose    
  5. Double-click the Close button and implement its Click event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
                Close();
    }
  6. Save all

The Read-Only Attribute

By default, a newly created text box is used to both display and receive text from the user. If you want the user to read text without being able to change it, set the ReadOnly Boolean property to True. Its default value is false.

Practical LearningPractical Learning: Setting the Read-Only Attribute

  1. On the form, click the text box at the intersection of Time and Regular
  2. In the Properties window, double-click ReadOnly to change its value to True
  3. Do the same for the following text boxes: txtRegularAmount, txtNetPay, txtOvertime, and txtOvertimeAmount

Auto-Completing a Text Box

If a text box allows the user to enter text in it, the user can click the control and start typing. If a certain text box usually receives some known or common strings, you can assist the user with completing the entry. The TextBox class supports this with three properties.

If you want to assist the user with completing the string entered in a text box, first specify where the necessary strings will come from. You have two options. You can use the AutoCompleteSource property, that is based on the AutoCompleteSource enumeration. Its members are: None, RecentlyUsedList, FileSystem, FileSystemDirectories, HistoryList, ListItems, AllSystemSources, AllUrl, and CustomSource.

If you want to specify your own-created list of items, use the AutoCompleteCustomSource property. At design time, to create a list of strings, access the Properties window for the text box. In the Properties window, click the ellipsis button of the AutoCompleteCustomSource field to open the String Collection Editor. Enter the strings separated by a hard Return, and click OK.

After specifying the source of the list that will assist the user to complete the entry of the text box, set it AutoCompleteMode property. This property is based on the AutoCompleteMode enumeration that has four members. None is the default value.

Practical LearningPractical Learning: Auto-Completing a Text Box

  1. On the form, click the txtEmployeeName text box
  2. In the Properties window, click AutoCompleteCustomSource and click its ellipsis button
  3. In the String Collection Editor, enter the following names:
    Micheline Hammond
    Paul Bertrand Yamaguchi
    Gertrude Monay
    Ernestine Ngaleu
    Andy Barang
    Christophe Yuen
    Jean Michel Kankan
  4. Click OK
  5. Click AutoCompleteSource, then click the arrow of its combo box and select CustomSource
  6. Click AutoCompleteMode, then click the arrow of its combo box and select Accept
  7. On the form, double-click the Calculate button and implement its event as follows:
     
    private void btnCalculate_Click(object sender, EventArgs e)
    {
            double monday1 = 0.00, tuesday1 = 0.00, wednesday1 = 0.00,
                        thursday1 = 0.00, friday1 = 0.00, saturday1 = 0.00,
                        sunday1 = 0.00, monday2 = 0.00, tuesday2 = 0.00,
                        wednesday2 = 0.00, thursday2 = 0.00,
             friday2 = 0.00, saturday2 = 0.00, sunday2 = 0.00;
             double totalHoursWeek1, totalHoursWeek2;
    
             double regHours1 = 0.00, regHours2 = 0.00,
                         ovtHours1 = 0.00, ovtHours2 = 0.00;
             double regAmount1 = 0.00, regAmount2 = 0.00,
                         ovtAmount1 = 0.00, ovtAmount2 = 0.00;
             double regularHours, overtimeHours;
             double regularAmount, overtimeAmount, totalEarnings;
    
             double hourlySalary = 0.00;
    
             // Retrieve the hourly salary
             try
             {
                    hourlySalary = double.Parse(txtHourlySalary.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show(
                        "The value you typed for the salary is invalid \n" +
                        "Please try again");
                    txtHourlySalary.Focus();
             }
    
             // Retrieve the value of each day worked
             try
             {
                    monday1 = double.Parse(txtMonday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                             "Please try again");
                    txtMonday1.Focus();
             }
             try
             {
                    tuesday1 = double.Parse(txtTuesday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    this.txtTuesday1.Focus();
             }
             try
             {
                    wednesday1 = double.Parse(txtWednesday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtWednesday1.Focus();
             }
             try
             {
                    thursday1 = double.Parse(txtThursday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtThursday1.Focus();
             }
    
             try
             {
                    friday1 = double.Parse(txtFriday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtFriday1.Focus();
             }
    
             try
             {
                    saturday1 = double.Parse(txtSaturday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtSaturday1.Focus();
             }
    
             try
             {
                    sunday1 = double.Parse(txtSunday1.Text);
             }
             catch (FormatException)
             {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtSunday1.Focus();
                }
                try
                {
                    monday2 = double.Parse(txtMonday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    this.txtMonday2.Focus();
                }
                try
                {
                    tuesday2 = double.Parse(txtTuesday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    this.txtTuesday2.Focus();
                }
                try
                {
                    wednesday2 = double.Parse(txtWednesday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    this.txtWednesday2.Focus();
                }
                try
                {
                    thursday2 = double.Parse(txtThursday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtThursday2.Focus();
                }
                try
                {
                    friday2 = double.Parse(txtFriday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtFriday2.Focus();
                }
                try
                {
                    saturday2 = double.Parse(txtSaturday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtSaturday2.Focus();
                }
                try
                {
                    sunday2 = double.Parse(txtSunday2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You typed an invalid value\n" +
                        "Please try again");
                    txtSunday2.Focus();
                }
    
                // Calculate the total number of hours for each week
                totalHoursWeek1 = monday1 + tuesday1 + wednesday1 +
                      thursday1 + friday1 + saturday1 + sunday1;
                totalHoursWeek2 = monday2 + tuesday2 + wednesday2 +
                    thursday2 + friday2 + saturday2 + sunday2;
    
                // The overtime is paid time and half
                double ovtSalary = hourlySalary * 1.5;
    
                // If the employee worked under 40 hours, there is no overtime
                if (totalHoursWeek1 < 40)
                {
                    regHours1 = totalHoursWeek1;
                    regAmount1 = hourlySalary * regHours1;
                    ovtHours1 = 0.00;
                    ovtAmount1 = 0.00;
                } // If the employee worked over 40 hours, calculate the overtime
                else if (totalHoursWeek1 >= 40)
                {
                    regHours1 = 40;
                    regAmount1 = hourlySalary * 40;
                    ovtHours1 = totalHoursWeek1 - 40;
                    ovtAmount1 = ovtHours1 * ovtSalary;
                }
    
                if (totalHoursWeek2 < 40)
                {
                    regHours2 = totalHoursWeek2;
                    regAmount2 = hourlySalary * regHours2;
                    ovtHours2 = 0.00;
                    ovtAmount2 = 0.00;
                }
                else if (totalHoursWeek2 >= 40)
                {
                    regHours2 = 40;
                    regAmount2 = hourlySalary * 40;
                    ovtHours2 = totalHoursWeek2 - 40;
                    ovtAmount2 = ovtHours2 * ovtSalary;
                }
    
                regularHours = regHours1 + regHours2;
                overtimeHours = ovtHours1 + ovtHours2;
                regularAmount = regAmount1 + regAmount2;
                overtimeAmount = ovtAmount1 + ovtAmount2;
                totalEarnings = regularAmount + overtimeAmount;
    
                txtRegularTime.Text = regularHours.ToString("F");
                txtOvertime.Text = overtimeHours.ToString("F");
                txtRegularAmount.Text = regularAmount.ToString("F");
                txtOvertimeAmount.Text = overtimeAmount.ToString("F");
    
                txtNetPay.Text = totalEarnings.ToString("F");
            }
  8. Execute the application to see the result
     
    Payroll Information
  9. Close the form and return to your programming environment

Character Casing

A text box can be configured to display only lowercase characters, only uppercase characters, or a mix. This characteristic is controlled by the CharacterCasing property, which is an enumerator that holds the same name. The default value of this property is Normal, which indicates that the control can use a mix of lowercase and uppercase characters. If you set this property to Lower, all existing characters, if any, in the control would be converted to lowercase and all future characters typed in the control would be automatically converted to lowercase. If you set this property to Upper, all existing characters, if any, in the control would be converted to uppercase and all future characters typed in the control would be automatically converted to uppercase.

Character Password

Text typed in a text box appears with its corresponding characters unless you changed the effect of the CharacterCasing property from its default Normal value. This allows the user to see, and be able to read, the characters of the control. If you prefer to make the characters un-readable, you have two options.

The operating system uses a default character it uses to hide the contents of a text box. If you want to use that character, set the UseSystemPasswordChar property to true. If you prefer to specify your own character, you can use the PasswordChar property. Although this property is a char type of data, changing it actually accomplishes two things:

  • If you type a character in its field in the Properties window, for example if you type *, any character typed in it would be un-readable
  • Any character in the control would be replaced by the value of this property. You can use any alphabetic character or digit to represent the characters that would be typed but you must provide only one character.
 
 

Previous Copyright © 2008-2009, yevol.com Next