Fundamental Controls

Introduction to the Button

An operating system provides you with the tools to interact with the computer. The visual tools are represented by graphic objects referred to as Windows controls, or controls. One of the most common controls is the button. The primary purpose of the button is to let you click to cause an action.

To support buttons, the .NET Framework provides the Button class. To visually create a button, in the Toolbox, click the Button control and click the form.

After visually adding a button to an application, you can configure it in the Properties window. Probably the two most important characteristics of a button are the text it displays and its Click event. To support its text, the Button class is equipped with the Text property. As for its Click event, you can simply double-click the button, and then write your code for the event.

Introduction to Labels

A text-based control is an object whose primary purpose is to display text. Like most operating systems, Microsoft Windows provides many controls, with various goals, to display text.

As the primary way to support text display, the .NET Framework provides a class named Label. It is available in the Toolbox by button of the same name. Therefore, to have a label in your application, you can click the Label control in the Toolbox and click the form. To dynamically create a label, declare a Label variable and initialize it with the new operator.

The primary job of a label is to display text. Therefore, the Label class is equipped with the Text property. An important characteristic of a label is to make its text fancy. To make this possible, you can customize its Font, its ForeColor, its BackColor, etc properties.

Practical LearningPractical Learning: Introducing the Label Controls

  1. Start Microsoft Visual Studio
  2. Create a new Windows Forms App named ElementaryAddition1
  3. In the Solution Explorer, right-click Form1.cs -> Rename
  4. Type ElementaryAddition (to get ElementaryAddition.cs) and press Enter twice
  5. Design the form as follows:

    Elementary Addition

    Elementary Addition

    Control (Name) BackColor Text Font ForeColor AutoSize
    Label Label lblOperand1   00 Times New Roman, 72pt, style=Bold Blue False
    Label Label     + Tahoma, 72pt, style=Bold Maroon  
    Label Label lblOperand2   00 Times New Roman, 72pt, style=Bold Blue False
    Label Label =   Dark Green Tahoma, 72pt, style=Bold Maroon  
    TextBox Text Box txtResult   000 Times New Roman, 72pt, style=Bold Blue  
    Label Label lblNewOperation Maroon New Operation Tahoma, 48pt, style=Bold White False
    Label Label lblCheck Maroon Check Times New Roman, 36pt, style=Bold White False
    Label Label     _____Close_____ Times New Roman, 48pt, style=Bold    
  6. On the form, double-click the New Operation label
  7. Return to the form and double-click the Check label
  8. Return to the form and double-click an unoccupied area of the form to generate its Load event
  9. Return to the form and double-click the Close label
  10. Change the document as follows:
    namespace ElementaryAddition1
    {
        public partial class ElementaryAddition : Form
        {
            public ElementaryAddition()
            {
                InitializeComponent();
            }
    
            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();
            }
    
            private void lblCheckAnswer_Click(object sender, EventArgs e)
            {
                int operand1 = int.Parse(lblOperand1.Text);
                int operand2 = int.Parse(lblOperand2.Text);
                
                int result = int.Parse(txtResult.Text);
    
                if (result == (operand1 + operand2))
                    MessageBox.Show("WOW - Good Answer", "Elementary Addition",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("Sorry - Wrong Answer", "Elementary Addition",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
                lblNewOperation_Click(sender, e);
            }
    
            private void ElementaryAddition_Load(object sender, EventArgs e)
            {
                lblNewOperation_Click(sender, e);
            }
    
            private void lblQuit_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  11. To execute again, on the main menu, click Debug -> Start Without Debugging:

    Elementary Addition

  12. Enter your answer in the text box. Here is an example:

    Elementary Addition

  13. Click the Check label. Here is an example:

    Elementary Addition

  14. Click the OK button on the message box and perform other operation
  15. Close the form and return to your programming environment

The Link Label

A link label is a special that allows you to create a connection from one object of an application, such as a form, to another object, such as another form.

Picture Controls

The Picture Box

A picture box is a control used to display a picture. The picture in one of the regular formats supported by most operating systems. The picture is put in a rectangular picture box with an initial size. In most cases, the picture box and the picture are originally not the same size. You can make the picture fit the picture box, you can make the picture box fit the picture, and you have many other options.

To support picture boxes, the .NET Framework provides a class named PictureBox. To add a picture box to your application, you can declare a variable of this object or, in the Toolbox, click the PictureBox button and click the form of your application.

Practical LearningPractical Learning: Introducing the Picture Box

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. Create a new Windows Forms App named AutoPartsInventory1
  3. In the Solution Explorer, right-click AutoPartsInventory1 -> Add -> New Folder
  4. Type Models as the name of the folder
  5. In the Solution Explorer, right-click Models -> Add -> Class...
  6. Type AutoPart as the name of the class
  7. Press Enter
  8. Complete the class as follows:
    namespace AutoPartsInventory1.Models
    {
        internal readonly struct AutoPart
        {
            internal long    PartNumber   { get; init; }
            internal string? PartCategory { get; init; }
            internal string? PartName     { get; init; }
            internal double  UnitPrice    { get; init; }
    
            public AutoPart()
                : this(100_000, "Generix", "Generic", 0.00d)
            {
    
            }
    
            public AutoPart(long number, string category,
                            string name, double price)
            {
                (PartNumber, PartCategory, PartName, UnitPrice) =
                    (number, category, name, price);
            }
        }
    }
    
  9. In the Solution Explorer, right-click Form1.cs -> Rename
  10. Type AutoPartsInventory (to get AutoPartsInventory.cs) and press Enter twice
  11. Design the form as follows:

    College Park Auto-Parts - Inventory - Form Design

    Controls (Name) Text Other Properties
    Label Label   Part Category: Font - Bold: True
    Label Label lblPartCategory   Font - Bold: True
    Label Label   Unit Price:  
    Label Label lblUnitPrice    
    Label Label   Part Name/Description:  
    Label Label lblPartName   Font - Bold: True
    PictureBox Picture Box pbxAutoPart   BorderStyle: FixedSingle
    SizeMode: AutoSize
  12. Double-click an unoccupied area of the form to launch its Load event
  13. Return to the form and double-click the picture box
  14. Return to the form and click an unoccupied area of its body
  15. In the Properties window, click the Events button Events
  16. In the Events section of the Properties window, double-click the Activated field
  17. Change the document as follows:
    using AutoPartsInventory1.Models;
    
    namespace AutoPartsInventory1
    {
        public partial class AutoPartsInventory : Form
        {
            internal AutoPart[]? AutoParts { get; set; }
    
            public AutoPartsInventory()
            {
                InitializeComponent();
            }
    
            private void AutoPartsInventory_Load(object sender, EventArgs e)
            {
                AutoParts = new AutoPart[25];
    
                AutoParts[0] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/283759.png
                    PartNumber = 283759,
                    PartCategory = "Starters",
                    PartName = "DB Electrical SND0787 Starter",
                    UnitPrice = 212.58
                };
    
                AutoParts[1] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/520384.png
                    PartNumber = 520384,
                    PartCategory = "Drum Brake",
                    PartName = "Rear Dynamic Friction Company True - Arc Brake Shoes",
                    UnitPrice = 42.22
    
                };
                AutoParts[2] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/927944.png
                    PartNumber = 927944,
                    PartCategory = "Bearings & Seals",
                    PartName = "Wheel Hub Bearing Assembly",
                    UnitPrice = 48.85
    
                };
                AutoParts[3] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/148040.png
                    PartNumber = 148040,
                    PartCategory = "Alternators & Generators",
                    PartName = "Alternator",
                    UnitPrice = 118.37
                };
                AutoParts[4] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/928037.png
                    PartNumber = 928037,
                    PartCategory = "Alternators & Generators",
                    PartName = "DB Electrical Alternator",
                    UnitPrice = 218.74
    
                };
                AutoParts[5] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/973947.png
                    PartNumber = 973947,
                    PartCategory = "Brake Kits",
                    PartName = "R1 Concepts Front Rear Brakes and Rotors Kit | Front Rear Brake Pads | Brake Rotors and Pads | Ceramic Brake Pads and Rotors",
                    UnitPrice = 292.84
    
                };
                AutoParts[6] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/730283.png
                    PartNumber = 730283,
                    PartCategory = "Oil Filters",
                    PartName = "Hydraulic Cylinder Timing Belt Tensioner",
                    UnitPrice = 14.15
                };
                AutoParts[7] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/593804.png
                    PartNumber = 593804,
                    PartCategory = "Alternators",
                    PartName = "Alternator",
                    UnitPrice = 202.47
    
                };
                AutoParts[8] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/639704.png
                    PartNumber = 639704,
                    PartCategory = "Brake Kits",
                    PartName = "Rear Brakes and Rotors Kit | Rear Brake Pads | Brake Rotors and Pads | Optimum OEp Brake Pads and Rotors",
                    UnitPrice = 125.15
    
                };
                AutoParts[9] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/740248.png
                    PartNumber = 740248,
                    PartCategory = "Bearings & Seals",
                    PartName = "Wheel hub bearing Assembly",
                    UnitPrice = 99.95
                };
                AutoParts[10] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/148073.png
                    PartNumber = 148073,
                    PartCategory = "Starters",
                    PartName = "DB Electrical SND0775 Starter",
                    UnitPrice = 94.48
                };
                AutoParts[11] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/297149.png
                    PartNumber = 297149,
                    PartCategory = "Air Filters",
                    PartName = "ACDelco Gold A3408C Air Filter",
                    UnitPrice = 297149
    
                };
                AutoParts[12] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/290741.png
                    PartNumber = 290741,
                    PartCategory = "Struts & Suspension",
                    PartName = "Front Strut and Coil Spring Assembly - Set of 2",
                    UnitPrice = 245.68
    
                };
                AutoParts[13] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/497249.png
                    PartNumber = 497249,
                    PartCategory = "Drum Brake",
                    PartName = "ACDelco Gold 17960BF1 Bonded Rear Drum Brake Shoe Set",
                    UnitPrice = 58.92
    
                };
                AutoParts[14] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/293748.png
                    PartNumber = 293748,
                    PartCategory = "Alternators",
                    PartName = "DB Electrical 400 - 40169 Alternator Compatible With / Replacement For 125 Internal Fan Type Decoupler Pulley Type Internal Regulator CW Rotation",
                    UnitPrice = 215.84
    
                };
                AutoParts[15] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/503502.png
                    PartNumber = 503502,
                    PartCategory = "Alternators",
                    PartName = "Alternator",
                    UnitPrice = 114.46
    
                };
                AutoParts[16] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/938475.png
                    PartNumber = 938475,
                    PartCategory = "Starters",
                    PartName = "DB Electrical SMT0343 Starter",
                    UnitPrice = 82.66
    
                };
                AutoParts[17] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/159937.png
                    PartNumber = 159937,
                    PartCategory = "Starters",
                    PartName = "DB Electrical SND0544 Starter",
                    UnitPrice = 88.88
    
                };
                AutoParts[18] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/520384.png
                    PartNumber = 520384,
                    PartCategory = "Starters",
                    PartName = "DB Electrical SND0775 Starter",
                    UnitPrice = 94.48
    
                };
                AutoParts[19] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/727394.png
                    PartNumber = 727394,
                    PartCategory = "Alternators",
                    PartName = "DB Electrical 400 - 40169 Alternator Compatible With / Replacement For 125 Internal Fan Type Decoupler Pulley Type Internal Regulator CW Rotation",
                    UnitPrice = 215.84
    
                };
                AutoParts[20] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/927937.png
                    PartNumber = 927937,
                    PartCategory = "Starters",
                    PartName = "Duralast Starter",
                    UnitPrice = 188.88
    
                };
                AutoParts[21] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/308113.png
                    PartNumber = 308113,
                    PartCategory = "Brake Kits",
                    PartName = "Autospecialty Front and Rear Replacement Brake Kit - OE Brake Rotors & Ceramic Brake Pads",
                    UnitPrice = 315.27
                };
                AutoParts[22] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/829385.png
                    PartNumber = 829385,
                    PartCategory = "Drum Brakes",
                    PartName = "Centric Brake Shoe",
                    UnitPrice = 829385
    
                };
                AutoParts[23] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/304031.png
                    PartNumber = 304031,
                    PartCategory = "Shocks, Struts & Suspension",
                    PartName = "Suspension Kit(Front; with 3 Groove Pitman Arm)",
                    UnitPrice = 142.44
    
                };
                AutoParts[24] = new AutoPart()
                {
                    // https://www.functionx.com/CollegeParkAutoParts/799428.png
                    PartNumber = 799428,
                    PartCategory = "Bearings & Seals",
                    PartName = "Front/Rear Wheel Hub Bearing Assembly 5 Lugs w/ ABS",
                    UnitPrice =   79.97
                };
            }
    
            private void pbxAutoPart_Click(object sender, EventArgs e)
            {
                Random rndNumber = new Random();
    
                int number = rndNumber.Next(0, 24);
    
                lblPartCategory.Text = AutoParts?[number].PartCategory;
                lblPartName.Text     = AutoParts?[number].PartName;
                lblUnitPrice.Text    = AutoParts?[number].UnitPrice.ToString();
                pbxAutoPart.Image    = Image.FromFile(@"E:\College Park Auto-Parts\" + AutoParts?[number].PartNumber.ToString() + ".png");
    
                Width = pbxAutoPart.Left + pbxAutoPart.Image.Width + 40;
                Height = pbxAutoPart.Top + pbxAutoPart.Image.Height + 60;
            }
    
            private void AutoPartsInventory_Activated(object sender, EventArgs e)
            {
                pbxAutoPart_Click(sender, e);
            }
        }
    }
  18. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    College Park Auto-Parts - Inventory

    College Park Auto-Parts - Inventory

    College Park Auto-Parts - Inventory

  19. Close the form and return to your programming environment
  20. Create a new Windows Forms App named AwesomeTires1
  21. In the Solution Explorer, right-click AwesomeTires1 < Manage NuGet Packages...
  22. In the NuGet tab, click Browse and, in the combo box, type VisualBasic
  23. In the resulting results, click Microsoft.VisualBasic
  24. Click Install.
    If the Preview Changes dialog box comes up, read it and click OK
  25. In the Solution Explorer, right-click AwesomeTires1 -> Add -> New Folder
  26. Type Models as the name of the folder
  27. To create a class, in the Solution Explorer, right-click Models -> Add -> Class...
  28. On the main menu, click Project -> Add Class...
  29. Replace the name with Employee
  30. Click Add
  31. Change the code as follows:
    namespace AwesomeTires1.Models
    {
        internal record class Employee(string EmployeeNumber,
                                       string EmployeeName,
                                       double BaseHourlyRate,
                                       double BaseTireRate)
        {
        }
    }
  32. To create another class, in the Solution Explorer, right-click Models -> Add -> Class...
  33. On the main menu, click Project -> Add Class...
  34. Replace the name with Payroll
  35. Click Add
  36. Change the code as follows:
    namespace AwesomeTires1.Models
    {
        internal record class Payroll
        {
            public long     PayrollNumber                          { get; init; }
            public string?  EmployeeNumber                         { get; init; }
            public (string? date, int tires, double pay) Monday    { get; init; }
            public (string? date, int tires, double pay) Tuesday   { get; init; }
            public (string? date, int tires, double pay) Wednesday { get; init; }
            public (string? date, int tires, double pay) Thursday  { get; init; }
            public (string? date, int tires, double pay) Friday    { get; init; }
            public int TotalTires
            {
                get
                {
                    return Monday.tires + Tuesday.tires + Wednesday.tires + Thursday.tires + Friday.tires;
                }
            }
            public double TotalPay
            {
                get
                {
                    return Monday.pay + Tuesday.pay + Wednesday.pay + Thursday.pay + Friday.pay;
                }
            }
        }
    }
  37. To create another class, in the Solution Explorer, right-click Models -> Add -> Class...
  38. On the main menu, click Project -> Add Class...
  39. Replace the name with Repository
  40. Click Add
  41. Change the code as follows:
    using Microsoft.VisualBasic;
    
    namespace TirePayroll1.Models
    {
        static internal class Repository
        {
            public static Collection Employees {get; set; }
            public static Collection Payrolls { get; set; }
    
            static Repository()
            {
                Employees = new Collection();
                Payrolls  = new Collection();
            }
        }
    }
  42. In the Solution Explorer, right-click AwesomeTires1 -> Add -> New Folder
  43. Type Employees as the name of the folder
  44. To create a form, in the Solution Explorer, right-click Employees -> Add -> Form(Windows Forms)...
  45. Type Create
  46. Press Enter

Text-Based Boxes

Introduction

A text box is a rectangular object that allows a user to type text, a number, etc in an application. You as the program can retrieve that value and use it any appropriate way you want.

To support text boxes, the .NET Framework provides a class named TextBoxBase that that is based on the Control class:

[System.ComponentModel.DefaultBindingProperty("Text")]
public abstract class TextBoxBase : System.Windows.Forms.Control

The TextBoxBase class provides all the common characteristics that text box controls need.

The Text Box

The most fundamental text box is a simple object made for relatively short strings and numbers. To make this control available, the .NET Framework provides a class named TextBox that that is derived from the TextBoxBase class:

public class TextBox : System.Windows.Forms.TextBoxBase

Based on this, to have a text box in your application, you can declare a variable of type TextBox. To visually add a text box to your application, in the Toolbox, click the TextBox control and click the form of your application. After creating a text box, you can configure its appearance in the Properties window or you can customize the control using code.

A Mask Text Box

A text box allows a user to type any type of character from the keyboard and to type those characters in any order. Depending on the type of application, this behavior can create a mess and confusion. A masked text box is a control made of small sections that are configured to allow and/or exclude other characters.

To help you restrict the type of characters that a user can put in a text box, the .NET Framework provides a class named MaskedTextBox:

[System.ComponentModel.DefaultBindingProperty("Text")]
public class MaskedTextBox : System.Windows.Forms.TextBoxBase

The masked text box is represented in the Toolbox as a control of the same name. Based on this, to create a masked text box, you can declare a variable of type MaskedTextBox or you can click the MaskedTextBox button in the Toolbox and click the form.

The most important part of a masked text box is the ability to make it accept some characters and reject others. To make this possible, the MaskedTextBox class is equipped with a property named Mask. Probably the best way to deal with this property is to configure it visually. To do this, access the Mask property in the Properties window. This would open a dialog box:

Input Mask

Using this dialog box, you can select one of the available formats or you can create one.

Practical LearningPractical Learning: Using the Masked Text Box

  1. In the Common Controls section of the Toolbox, click MaskedTextBox and click the form
  2. Complete the design of the form as follows:

    Awesome Tires - New Employee

    Control (Name) Text Other Properties
    Label Label   &Employee #:  
    MaskedTextBox Masked Text Box mtbEmployeeNumber   Masked: 000-000
    Modifiers: Public
    Label Label   Employee &Name:  
    TextBox Text Box txtEmployeeName   Modifiers: Public
    Label Label   Base &Hourly Rate:  
    TextBox Text Box txtBaseHourlyRate   Modifiers: Public
    Label Label   Base &Tire Rate:  
    TextBox Text Box txtBaseTireRate   Modifiers: Public
    Button Button btnSaveEmployee S&ave Employee Record DialogResult: OK
    Button Button btnClose &Close DialogResult: Cancel
  3. Click an unoccupied area of the form and, in the Properties window, set the folowing valus:
    AcceptButton: btnSaveEmployee
    CancelButton: btnClose
  4. To create another form, in the Solution Explorer, right-click Employees -> Add -> Form(Windows Forms)...
  5. Type ViewAll
  6. Press Enter
  7. In the Toolbox, click the ListView button and click the form
  8. On the form, right-click the list view and click Edit Columns...
  9. Create the columns as follows:
    (Name) Text TextAlign Width
    colEmployeeId Id   40
    colEmployeeNumber Employee # Center 150
    colEmployeeName Employee Name   250
    colBaseHourlyRate Base Hourly Rate Center 150
    colBaseTireRate Base Tire Rate Center 125
  10. Click OK
  11. Complete the design of the form as follows:

    Awesome Tires - Employees

    Control (Name) Text Other Properties
    ListView List View lvwEmployees   FullRowSelect: True
    GridLines: True
    View: Details
    Button Button btnNewEmployee &New Employee...  
    Button Button btnClose &Close  
  12. Double-click an unoccupied area of the form
  13. Return to the form and double-click the &New Employee... button
  14. Return to the form and double-click the &Close button
  15. Change the document as follows:
    using AwesomeTires1.Models;
    
    namespace AwesomeTires1.Employees
    {
        public partial class ViewAll : Form
        {
            public ViewAll()
            {
                InitializeComponent();
            }
    
            private void ShowEmployees()
            {
                lvwEmployees.Items.Clear();
    
                int counter = 1;
    
                foreach (Employee empl in Repository.Employees)
                {
                    ListViewItem lviEmployee = new ListViewItem(counter++.ToString());
    
                    lviEmployee.SubItems.Add(empl.EmployeeNumber);
                    lviEmployee.SubItems.Add(empl.EmployeeName);
                    lviEmployee.SubItems.Add(empl.BaseHourlyRate.ToString());
                    lviEmployee.SubItems.Add(empl.BaseTireRate.ToString());
                    lvwEmployees.Items.Add(lviEmployee);
                }
            }
    
            private void ViewAll_Load(object sender, EventArgs e)
            {
                ShowEmployees();
            }
    
            private void btnNewEmployee_Click(object sender, EventArgs e)
            {
                Create hire = new();
    
                if (hire.ShowDialog() == DialogResult.OK)
                {
                    if (string.IsNullOrEmpty(hire.mtbEmployeeNumber.Text))
                    {
                        MessageBox.Show("You must enter the employee number.",
                                        "Awesome Tires",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
    
                    Employee staff = new Employee(hire.mtbEmployeeNumber.Text,
                                                  hire.txtEmployeeName.Text,
                                                  double.Parse(hire.txtBaseHourlyRate.Text),
                                                  double.Parse(hire.txtBaseTireRate.Text));
                    Repository.Employees.Add(staff);
                }
    
                ShowEmployees();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  16. In the Solution Explorer, right-click AwesomeTires1 -> Add -> New Folder
  17. Type Payrolls as the name of the folder
  18. To create a form, in the Solution Explorer, right-click Payrolls -> Add -> Form(Windows Forms)...
  19. Type Create
  20. Click Add
  21. Design the form as follows:

    Awesome Tires - Payroll Processing

    Control (Name) Text TextAlign Mask
    Label Label   &Payroll #:    
    TextBox Text Box txtPayrollNumber    
    Label Label   &Employee #:    
    MaskedTextBox Masked Text Box mtbEmployeeNumber   Masked: 000-000
    Button Button btnFindEmployee &Find Employee    
    Label Label   Employee &Name:    
    TextBox Text Box txtEmployeeName    
    Label Label   Base Rate - &Hourly:    
    TextBox Text Box txtBaseHourlyRate    
    Label Label   Per &Tire:    
    TextBox Text Box txtBaseTireRate    
    GroupBox Masked Text Box   Work Summary
    Label Label   Day Worked:    
    Label Label   Tires Installed    
    Label Label   Day Pay    
    Label Label   Monday:    
    MaskedTextBox Masked Text Box mtbMondayDate   Masked: Short date
    TextBox Text Box txtMondayTires    
    Button Button btnMonday =    
    TextBox Text Box txtMondayPay   Public  
    Label Label   Tuesday:    
    MaskedTextBox Masked Text Box mtbTuesdayDate   Masked: Short date
    TextBox Text Box txtTuesdayTires    
    Button Button btnTuesday =    
    TextBox Text Box txtTuesdayPay    
    Label Label   Wednesday:    
    MaskedTextBox Masked Text Box mtbWednesdayDate   Masked: Short date
    TextBox Text Box txtWednesdayTires    
    Button Button btnWednesday =    
    TextBox Text Box txtWednesdayPay    
    Label Label   Thursday:    
    MaskedTextBox Masked Text Box mtbThursdayDate   Masked: Short date
    TextBox Text Box txtThursdayTires    
    Button Button btnThursday =    
    TextBox Text Box txtThursdayPay    
    Label Label   Friday:    
    MaskedTextBox Masked Text Box mtbFridayDate   Masked: Short date
    TextBox Text Box txtFridayTires    
    Button Button btnFriday =    
    TextBox Text Box txtFridayPay   Public  
    Label Label   _________________________    
    Label Label   Total Tires && Pay:    
    TextBox Text Box txtotalTires    
    TextBox Text Box txtotalPay    
    Button Button btnSavePayroll S&ave Payroll    
    Button Button btnClose &Close    
  22. Double-click the Find Employee button
  23. Return to the form and double-click the = button on the Monday line
  24. Return to the form and double-click the = button on the Tuesday line
  25. Return to the form and double-click the = button on the Wednesday line
  26. Return to the form and double-click the = button on the Thursday line
  27. Return to the form and double-click the = button on the Friday line
  28. Return to the form and double-click the Save Payroll button
  29. Return to the form and double-click the Close button
  30. Change the document as follows:
    using AwesomeTires1.Models;
    
    namespace AwesomeTires1.Payrolls
    {
        public partial class Create : Form
        {
            public Create()
            {
                InitializeComponent();
            }
    
            private void btnFindEmployee_Click(object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(mtbEmployeeNumber.Text))
                {
                    MessageBox.Show("You must enter the employee number.",
                                    "Awesome Tires",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
    
                foreach (Employee staff in Repository.Employees)
                {
                    if (staff.EmployeeNumber.Equals(mtbEmployeeNumber.Text))
                    {
                        txtEmployeeName.Text   = staff.EmployeeName;
                        txtBaseHourlyRate.Text = staff.BaseHourlyRate.ToString();
                        txtBaseTireRate.Text   = staff.BaseTireRate.ToString();
                        break;
                    }
                }
            }
    
            private double EvaluatePay(in string strHourlyRate, in string strTireRate, in string strNumberOfTires)
            {
                if (string.IsNullOrEmpty(strHourlyRate))
                {
                    MessageBox.Show("You must first type a valid employee number and click Find Employee.",
                                    "Awesome Tires",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return 0.00;
                }
    
                if (string.IsNullOrEmpty(strTireRate))
                {
                    MessageBox.Show("You must first type a valid employee number and click Find Employee.",
                                    "Awesome Tires",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return 0.00;
                }
    
                if (string.IsNullOrEmpty(strNumberOfTires))
                {
                    MessageBox.Show("You must enter the number of tires that the employee installed on Monday.",
                                    "Awesome Tires",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return 0.00;
                }
    
                int tires = 0;
    
                try
                {
                    tires = int.Parse(strNumberOfTires);
                }
                catch (FormatException fe)
                {
                    MessageBox.Show("The number of tires installed for the day is not valid. " +
                                    "The error produced is: " + fe.Message,
                                    "Awesome Tires",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
    
                double payBasedOnTires = double.Parse(txtBaseTireRate.Text)   * tires;
                double dailySalary     = double.Parse(txtBaseHourlyRate.Text) * 8.00;
    
                double pay = payBasedOnTires;
    
                if(payBasedOnTires < dailySalary)
                {
                    pay = dailySalary;
                }
    
                return pay;
            }
    
            private void CalculateTotal()
            {
                int tireMonday      = 0, tireTuesday = 0, tireWednesday = 0, tireThursday = 0, tireFriday = 0;
                double payMonday    = 0d, payTuesday = 0d, payWednesday = 0d, payThursday = 0d, payFriday = 0d;
    
                try { tireMonday    = int.Parse(txtMondayTires.Text);     } catch { }
                try { tireTuesday   = int.Parse(txtTuesdayTires.Text);    } catch { }
                try { tireWednesday = int.Parse(txtWednesdayTires.Text);  } catch { }
                try { tireThursday  = int.Parse(txtThursdayTires.Text);   } catch { }
                try { tireFriday    = int.Parse(txtFridayTires.Text);     } catch { }
    
                try { payMonday     = double.Parse(txtMondayPay.Text);    } catch { }
                try { payTuesday    = double.Parse(txtTuesdayPay.Text);   } catch { }
                try { payWednesday  = double.Parse(txtWednesdayPay.Text); } catch { }
                try { payThursday   = double.Parse(txtThursdayPay.Text);  } catch { }
                try { payFriday     = double.Parse(txtFridayPay.Text);    } catch { }
    
                int totalTires      = tireMonday + tireTuesday + tireWednesday + tireThursday + tireFriday;
                double totalPay     = payMonday  + payTuesday  + payWednesday  + payThursday  + payFriday;
    
                txtTotalTires.Text  = totalTires.ToString();
                txtTotalPay.Text    = totalPay.ToString("n");
            }
    
            private void btnMonday_Click(object sender, EventArgs e)
            {
                double dMondayPay = EvaluatePay(txtBaseHourlyRate.Text, txtBaseTireRate.Text, txtMondayTires.Text);
    
                txtMondayPay.Text = dMondayPay.ToString("n");
                CalculateTotal();
            }
    
            private void btnTuesday_Click(object sender, EventArgs e)
            {
                double dTuesdayPay = EvaluatePay(txtBaseHourlyRate.Text, txtBaseTireRate.Text, txtTuesdayTires.Text);
    
                txtTuesdayPay.Text = dTuesdayPay.ToString("n");
                CalculateTotal();
            }
    
            private void btnWednesday_Click(object sender, EventArgs e)
            {
                double dWednesdayPay = EvaluatePay(txtBaseHourlyRate.Text, txtBaseTireRate.Text, txtWednesdayTires.Text);
    
                txtWednesdayPay.Text = dWednesdayPay.ToString("n");
                CalculateTotal();
            }
    
            private void btnThursday_Click(object sender, EventArgs e)
            {
                double dThursdayPay = EvaluatePay(txtBaseHourlyRate.Text, txtBaseTireRate.Text, txtThursdayTires.Text);
    
                txtThursdayPay.Text = dThursdayPay.ToString("n");
                CalculateTotal();
            }
    
            private void btnFriday_Click(object sender, EventArgs e)
            {
                double dFridayPay = EvaluatePay(txtBaseHourlyRate.Text, txtBaseTireRate.Text, txtFridayTires.Text);
    
                txtFridayPay.Text = dFridayPay.ToString("n");
                CalculateTotal();
            }
    
            private void btnSavePayroll_Click(object sender, EventArgs e)
            {
                Payroll payroll    = new Payroll()
                {
                    PayrollNumber  = long.Parse(txtPayrollNumber.Text),
                    EmployeeNumber = mtbEmployeeNumber.Text,
                    Monday         = (mtbMondayDate.Text,    int.Parse(txtMondayTires.Text),    double.Parse(txtMondayPay.Text)),
                    Tuesday        = (mtbTuesdayDate.Text,   int.Parse(txtTuesdayTires.Text),   double.Parse(txtTuesdayPay.Text)),
                    Wednesday      = (mtbWednesdayDate.Text, int.Parse(txtWednesdayTires.Text), double.Parse(txtWednesdayPay.Text)),
                    Thursday       = (mtbThursdayDate.Text,  int.Parse(txtThursdayTires.Text),  double.Parse(txtThursdayPay.Text)),
                    Friday         = (mtbFridayDate.Text,    int.Parse(txtFridayTires.Text),    double.Parse(txtFridayPay.Text)),
                };
    
                Repository.Payrolls.Add(payroll);
                Close();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  31. To create a form, in the Solution Explorer, right-click Payrolls -> Add -> Form(Windows Forms)...
  32. Type View
  33. Click Add
  34. Resize the form to give it approximaely the same size as the Create form
  35. Copy all the controls from the Create form and paste them in the View form
  36. On the View form, delete all the = and the Save Payroll buttons
  37. Complete the design of the form as follows:

    Awesome Times - View Payroll

    Control (Name) Text
    Button Button btnFindPayroll &Find Payroll
    Button Button btnClose &Close
  38. On the form, double-click the Find Payroll button
  39. Return to the form and double-click the Close button
  40. Change the document as follows:
    using AwesomeTires1.Models;
    
    namespace AwesomeTires1.Payrolls
    {
        public partial class View : Form
        {
            public View()
            {
                InitializeComponent();
            }
    
            private void btnFindPayroll_Click(object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(txtPayrollNumber.Text))
                {
                    MessageBox.Show("You must enter a payroll number.",
                                    "Awesome Tires",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
    
                foreach (Payroll pay in Repository.Payrolls)
                {
                    if (pay.PayrollNumber.Equals(long.Parse(txtPayrollNumber.Text)))
                    {
                        mtbEmployeeNumber.Text = pay.EmployeeNumber;
    
                        mtbMondayDate.Text     = pay.Monday.date;
                        txtMondayTires.Text    = pay.Monday.tires.ToString();
                        txtMondayPay.Text      = pay.Monday.pay.ToString();
    
                        mtbTuesdayDate.Text    = pay.Tuesday.date;
                        txtTuesdayTires.Text   = pay.Tuesday.tires.ToString();
                        txtTuesdayPay.Text     = pay.Tuesday.pay.ToString();
    
                        mtbWednesdayDate.Text  = pay.Wednesday.date;
                        txtWednesdayTires.Text = pay.Wednesday.tires.ToString();
                        txtWednesdayPay.Text   = pay.Wednesday.pay.ToString();
    
                        mtbThursdayDate.Text   = pay.Thursday.date;
                        txtThursdayTires.Text  = pay.Thursday.tires.ToString();
                        txtThursdayPay.Text    = pay.Thursday.pay.ToString();
    
                        mtbFridayDate.Text     = pay.Friday.date;
                        txtFridayTires.Text    = pay.Friday.tires.ToString();
                        txtFridayPay.Text      = pay.Friday.pay.ToString();
    
                        txtTotalTires.Text     = pay.TotalTires.ToString();
                        txtTotalPay.Text       = pay.TotalPay.ToString();
                        break;
                    }
                }
    
                foreach (Employee staff in Repository.Employees)
                {
                    if (staff.EmployeeNumber.Equals(mtbEmployeeNumber.Text))
                    {
                        txtEmployeeName.Text   = staff.EmployeeName;
                        txtBaseHourlyRate.Text = staff.BaseHourlyRate.ToString();
                        txtBaseTireRate.Text   = staff.BaseTireRate.ToString();
                        break;
                    }
                }
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  41. In the Solution Explorer, right-click Form1.cs -> Rename
  42. Type TiresInstallation (to get TiresInstallation.cs) and press Enter three times
  43. Design the form as follows:

    Awesome Times - Switchboard

    Control (Name) Text
    Button Button btnPreparePayroll &Prepare Payroll...
    Button Button btnViewPayroll &View Payroll...
    Button Button btnEmployees &Employees...
    Button Button btnClose &Close
  44. On the form, double-click the Prepare Payroll... button
  45. Return to the form and double-click the View Payroll... button
  46. Return to the form and double-click the Employees... button
  47. Return to the form and double-click the Close button
  48. Implement the events as follows:
    namespace AwesomeTires1
    {
        public partial class TiresInstallation : Form
        {
            public TiresInstallation()
            {
                InitializeComponent();
            }
    
            private void btnPreparePayroll_Click(object sender, EventArgs e)
            {
                Payrolls.Create create = new Payrolls.Create();
    
                create.ShowDialog();
            }
    
            private void btnViewPayroll_Click(object sender, EventArgs e)
            {
                Payrolls.View view = new Payrolls.View();
                view.Show();
            }
    
            private void btnEmployees_Click(object sender, EventArgs e)
            {
                Employees.ViewAll employees = new Employees.ViewAll();
                employees.Show();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  49. To execute, on the main menu, click Debug -> Start Without Debugging
  50. Click the Employees button
  51. Click New Employee button:

    Awesome Tires - New Employee

  52. Create a few records as follows:
    Employee # Employee Name Base Hourly Rate Base Tire Rate
    206-805 David Flore 14.26 1.08
    935-069 Mark Stanley Lochlear 12.85 1.42
    395-797 Marguerite Ashley Norris 15.05 0.97
    139-579 Ronaldo Franky Rodriguez 15.86 1.32
    503-580 Thomas Wells 13.88 1.62
    759-742 Annabella Hernadez 16.41 0.86

    Awesome Tires - Employees

  53. Close the Employees form
  54. Click the Prepare Payroll button

    Awesome Tires - Payrolls

  55. Fill the form with the following values:
    Payroll #:	948575
    Employee #:	395-797
    Monday:
        Work Date:	07/10/2023
        # of Tires:	118
    Tuesday:
        Work Date:  07/11/2023
        # of Tires:	46
    Wednesday:
        Work Date:	07/12/2023
        # of Tires:	125
    Thursday:
        Work Date:  07/13/2023
        # of Tires	52
    Friday:
        Work Date:	07/14/2023
        # of Tires: 97
  56. Click Find Employee
  57. Click each = button:

    Awesome Tires - Payroll Preparation

  58. Click Save Payroll
  59. Click the Prepare Payroll button
  60. Fill the form with the following values:
    Payroll #:	297203
    Employee #:	139-579
    Monday:
        Work Date:	07/17/2023
        # of Tires:	97
    Tuesday:
        Work Date:  07/18/2023
        # of Tires:	122
    Wednesday:
        Work Date:	07/19/2023
        # of Tires:	131
    Thursday:
        Work Date:  07/20/2023
        # of Tires	116
    Friday:
        Work Date:	07/21/2023
        # of Tires: 126
  61. Click Find Employee
  62. Click each Find Payroll button:

    Awesome Tires - Payroll Preparation

  63. Click Save Payroll
  64. Click View Payroll
  65. In the Payroll # text box, type 948575
  66. Click Find Payroll
  67. Close the View Payroll form
  68. Close the forms and return to your programming environment

A Text Editor

A text editor is a special version of a text box. While the classical text box is made for only one line of text, a text editor can handle many lines. When its content is long, a text editor can be equipped with scroll bars (at least vertical scroll bars) to make it possible for the user to navigate up and down within the text.

To start a text editor, declare a TextBox variable or add a TextBox control to a form. The most fundamental property that differentiates a classic text box and a text editor is Boolean and it is named Multiline:

public override bool Multiline { get; set; }

Although the Multiline Boolean property is the most important characteristic of a text editor, the control may need other functionalities, such as scroll bars available through a property named ScrollBars:

public System.Windows.Forms.ScrollBars ScrollBars { get; set; }

Of course, you can set this property visually in the Properties window or programmatically.

A Rich Text Box

A text box displays all its characters in only one font and all characters are painted in the same color. A rich text box can display some of its characters in one font and some other characters in other fonts. Also, some characters can be made to display in different colors.

To support rich text boxes, the .NET Framework provides a class named RichTextBox that is derived from TextBoxBase:

[System.Windows.Forms.Docking(System.Windows.Forms.DockingBehavior.Ask)]
public class RichTextBox : System.Windows.Forms.TextBoxBase

Although both the TextBox and the RichTextBox have a common parent (the TextBoxBase), and the regular text box produces a text editor, the rich text box is an enahnced version of the text editor. Therefore, if you want a multi-line text editor that can handle colors and various types of fonts, declare a variable of type RichTextBox. To graphically create a rich text box, in the Toolbox, click the RichTextBox button and click a form. If you visually create a rich text box, you can partially configure it in the Properties window. Some of the behaviors, such as displaying some sections of the text in different colors or different fonts, can be handled only by writing code.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Thursday 22 September 2022 Next