Home

Application Application: College Parc Auto-Repair

Introduction

A data grid view is a flexible control that makes it possible to display a collection of values. This application explores some of its features, including the ability the save the values of a data grid view in a regular text-based file.

Practical LearningApplication: Creating the Application

  1. Start Microsoft Visual C#
  2. Create a new Windows Application named CollegeParkAutoRepair1
  3. In the Solution Explorer, right-click Form1.cs and click Rename
  4. Type CollegeParkAutoRepair.cs and press Enter
  5. In the Menus & Toolbars section of the Toolbox, click MenuStrip and click the form
  6. Under the form, right-click menuStrip1 and click Insert Standard Items
  7. In the Menus & Toolbars section of the Toolbox, click StatusStrip and click the form
  8. Design the form as follows:
     

    College Park Auto Repair

    Control Name Text Other Properties
    GroupBox GroupBox   Order Identification  
    Label Label   Customer Name:  
    TextBox TextBox txtCustomerName    
    Label Label   Address  
    TextBox TextBox txtAddress    
    Label Label   City:  
    TextBox TextBox txtCity    
    Label Label   State:  
    TextBox TextBox txtState    
    Label Label   ZIP Code:  
    TextBox TextBox txtZIPCode   TextAlign: Right
    Label Label   Make / Model:  
    TextBox TextBox txtMake    
    TextBox TextBox txtModel    
    Label Label   Year:  
    TextBox TextBox txtCarYear   TextAlign: Right
    Label Label   Problem Description:  
    TextBox TextBox txtProblem   Mutltiline: True
    GroupBox GroupBox   Parts Used  
    DataGridView DataGridView dgvPartsUsed    
    Columns  
    Header Text Name Width
    Part Name/Description colPartName 215
    Unit Price colUnitPrice 80
    Qty colQuantity 30
    Sub-Total colSubTotal 60
    GroupBox GroupBox   Jobs Performed  
    DataGridView DataGridView dgvJobsPerformed    
    Columns  
    Header Text Name Width
    Job Performed colJobPerformed 320
    Cost colCost 60
    GroupBox GroupBox   Repair Summary  
    Label Label   Total Parts:  
    TextBox TextBox txtTotalParts 0.00 TextAlign: Right
    Label Label   Tax Rate:  
    TextBox TextBox txtTaxRate 5.75 TextAlign: Right
    Label Label   %  
    Label Label   Total Labor:  
    TextBox TextBox txtTotalLabor 0.00 TextAlign: Right
    Label Label   Tax Amount:  
    TextBox TextBox txtTaxAmount 0.00 TextAlign: Right
    Label Label   RepairTotal:  
    TextBox TextBox txtRepairTotal 0.00 TextAlign: Right
    Label Label   Recommendations  
    TextBox TextBox txtRecommendations   Multiline: True
    OpenFileDialog OpenFileDialog dlgOpen   DefaultExt: rpr
    Filter: Repair Orders (*.rpr)|*.rpr|All Files|
    Title: Open Existing Repair Order
    SaveFileDialog SaveFileDialog dlgSave  

    DefaultExt: rpr
    Filter: Repair Orders (*.rpr)|*.rpr|All Files|
    Title: Save Current Repair Order

    PrintDocument PrintDocument docPrint  

     

    PrintDialog PrintDialog dlgPrint   

    Document: docPrint

    PageSetupDialog Page Setup Dialog dlgPageSetup   Document: docPrint
    PrintPreviewDialog Print Preview Dialog dlgPrintPreview   Document: docPrint
  9. On the form, click the data grid view in the Parts Used group
  10. In the properties window, click Events and double-click CellLeave
  11. Implement the event as follows:
    void CalculateTotal()
    {
        double taxRate = 0d, taxAmount = 0d;
        double totalParts = 0d, totalLabor = 0d, totalPartsAndLabor, repairTotal;
    
        foreach( DataGridViewRow record in dgvPartsUsed.Rows)
        {
            try
            {
                totalParts += double.Parse(record.Cells[3].EditedFormattedValue.ToString());
                txtTotalParts.Text = totalParts.ToString("F");
            }
            catch (FormatException)
            {
            }
        }
    
        foreach (DataGridViewRow record in dgvJobsPerformed.Rows)
        {
            try
            {
                totalLabor += double.Parse(record.Cells[1].EditedFormattedValue.ToString());
                txtTotalLabor.Text = totalLabor.ToString("F");
            }
            catch (FormatException)
            {
            }
        }
    
        try
        {
            taxRate = double.Parse(txtTaxRate.Text);
        }
        catch (FormatException)
        {
            MessageBox.Show("Invalid Tax Rate");
            txtTaxRate.Text = "5.75";
            txtTaxRate.Focus();
        }
    
        totalPartsAndLabor = totalParts + totalLabor;
    
        taxAmount = totalPartsAndLabor * taxRate / 100;
        repairTotal = totalPartsAndLabor + taxAmount;
    
        txtTotalParts.Text = totalParts.ToString("F");
        txtTotalLabor.Text = totalLabor.ToString("F");
        txtTaxAmount.Text = taxAmount.ToString("F");
        txtRepairTotal.Text = repairTotal.ToString("F");
    }
    
    private void dgvPartsUsed_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 2)
        {
            double unitPrice = 0D;
            int quantity = 0;
            double subTotal = 0D;
            
            DataGridViewCell dgvcUnitPrice = dgvPartsUsed.Rows[e.RowIndex].Cells[1];
            DataGridViewCell dgvcQuantity = dgvPartsUsed.Rows[e.RowIndex].Cells[e.ColumnIndex];
    
            unitPrice = double.Parse(dgvcUnitPrice.EditedFormattedValue.ToString());
            quantity = int.Parse(dgvcQuantity.EditedFormattedValue.ToString());
            subTotal = unitPrice * quantity;
            dgvPartsUsed.Rows[e.RowIndex].Cells[3].Value = subTotal.ToString("F");
    
            CalculateTotal();
        }
    }
  12. Return to the form
  13. Click the Jobs Performed data grid view
  14. In the Events section of the properties window, double-click CellLeave
  15. Implement the event as follows:
    private void dgvJobsPerformed_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        CalculateTotal();
    }
  16. Return to the form
  17. On the form, click File and double-click New Repair Order
  18. Implement its Click event as follows:
    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
        txtCustomerName.Text = "";
        txtAddress.Text = "";
        txtCity.Text = "";
        txtState.Text = "";
        txtZIPCode.Text = "";
        txtMake.Text = "";
        txtModel.Text = "";
        txtYear.Text = "";
        txtProblemDescription.Text = "";
    
        dgvPartsUsed.Rows.Clear();
        dgvJobsPerformed.Rows.Clear();
    
        txtTotalParts.Text = "0.00";
        txtTotalLabor.Text = "0.00";
        txtTaxRate.Text = "7.75";
        txtTaxAmount.Text = "0.00";
        txtRepairTotal.Text = "0.00";
    
        txtRecommendations.Text = "";
        txtCustomerName.Focus();
    }
  19. In the top section of the file, type the following:
    using System;
    using System.ComponentModel;
    using System.Collections;
    using System.Windows.Forms;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
  20. Return to the form
  21. On the form, click File and double-click Save As...
  22. Implement its Click event as follows:
    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Just in case, calculate the order now
        CalculateTotal();
    
        // Check the folder that will contain the repair order.
        // If it exists, don't create it.
        // If it doesn't exist, then create it
        string strDirectory = @"C:\College Park Auto Repair";
        DirectoryInfo dirInfo = Directory.CreateDirectory(strDirectory);
    
        // Prepare to create a repair order
        RepairOrder order = new RepairOrder();
    
    
        // Display the Save As dialog box.
        // Select the above directory
        dlgSave.InitialDirectory = strDirectory;
        // Check if the user clicked OK
        if (dlgSave.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            // If the user clicked OK, create a repair order
            order.CustomerName = txtCustomerName.Text;
            order.Address = txtAddress.Text;
            order.City = txtCity.Text;
            order.State = txtState.Text;
            order.ZIPCode = txtZIPCode.Text;
            order.Make = txtMake.Text;
            order.Model = txtModel.Text;
            order.Year = int.Parse(txtYear.Text);
            order.ProblemDescription = txtProblemDescription.Text;
    
            // Check whether the Parts Used data grid view contains some records.
            // If it does, save them
            if (dgvPartsUsed.Rows.Count > 1)
            {
                List<Part> parts = new List<Part>();
    
                for (int row = 0; row < dgvPartsUsed.Rows.Count - 1; row++ )
                {
                    Part prt = new Part();
                    prt.PartName = dgvPartsUsed.Rows[row].Cells[0].EditedFormattedValue.ToString();
                    prt.UnitPrice = double.Parse(dgvPartsUsed.Rows[row].Cells[1].EditedFormattedValue.ToString());
                    prt.Quantity = int.Parse(dgvPartsUsed.Rows[row].Cells[2].EditedFormattedValue.ToString());
                    prt.SubTotal = double.Parse(dgvPartsUsed.Rows[row].Cells[3].EditedFormattedValue.ToString());
                    parts.Add(prt);
                }
                order.Parts = parts;
            }
            else // If the data grid view is empty, flag its value as null
                order.Parts = null;
    
            if (dgvJobsPerformed.Rows.Count > 1)
            {
                List<JobPerformed> work = new List<JobPerformed>();
    
                for (int row = 0; row < dgvJobsPerformed.Rows.Count - 1; row++)
                {
                    JobPerformed done = new JobPerformed();
                    done.Job = dgvJobsPerformed.Rows[row].Cells[0].EditedFormattedValue.ToString();
                    done.Cost = double.Parse(dgvJobsPerformed.Rows[row].Cells[1].EditedFormattedValue.ToString());
                    work.Add(done);
                }
    
                order.Jobs = work;
            }
    
            order.TotalParts = double.Parse(txtTotalParts.Text);
            order.TotalLabor = double.Parse(txtTotalLabor.Text);
            order.TaxRate = double.Parse(txtTaxRate.Text);
            order.TaxAmount = double.Parse(txtTaxAmount.Text);
            order.RepairTotal = double.Parse(txtRepairTotal.Text);
            order.Recommendations = txtRecommendations.Text;
    
            FileStream stmRepair = new FileStream(dlgSave.FileName,
                                                       FileMode.Create);
            BinaryFormatter bfmRepair = new BinaryFormatter();
            bfmRepair.Serialize(stmRepair, order);
    
            stmRepair.Close();
            newToolStripMenuItem_Click(sender, e);
        }
    }
  23. Return to the form
  24. On the form, click File and double-click Open...
  25. Implement the event as follows:
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        dlgOpen.InitialDirectory = @"C:\College Park Auto Repair";
    
        if (dlgOpen.ShowDialog() == DialogResult.OK)
        {
            FileStream stmRepair = new FileStream(dlgOpen.FileName,
                                             FileMode.Open);
            BinaryFormatter bnrRepair = new BinaryFormatter();
            RepairOrder order = (RepairOrder)bnrRepair.Deserialize(stmRepair);
    
            txtCustomerName.Text = order.CustomerName;
            txtAddress.Text      = order.Address;
            txtCity.Text         = order.City;
            txtState.Text        = order.State;
            txtZIPCode.Text      = order.ZIPCode;
            txtMake.Text         = order.Make;
            txtModel.Text        = order.Model;
            txtYear.Text         = order.Year.ToString();
            txtProblemDescription.Text = order.ProblemDescription;
    
            int i = 0;
            foreach (Part prt in order.Parts)
            {
                dgvPartsUsed.Rows.Add();
    
                dgvPartsUsed.Rows[i].Cells[0].Value = prt.PartName;
                dgvPartsUsed.Rows[i].Cells[1].Value = prt.UnitPrice.ToString("F");
                dgvPartsUsed.Rows[i].Cells[2].Value = prt.Quantity.ToString();
                dgvPartsUsed.Rows[i].Cells[3].Value = prt.SubTotal.ToString("F");
                i++;
            }
    
            i = 0;
            foreach (JobPerformed jp in order.Jobs)
            {
                dgvJobsPerformed.Rows.Add();
    
                dgvJobsPerformed.Rows[i].Cells[0].Value = jp.Job;
                dgvJobsPerformed.Rows[i].Cells[1].Value = jp.Cost;
                i++;
            }
    
            txtTotalParts.Text  = order.TotalParts.ToString("F");
            txtTotalLabor.Text  = order.TotalLabor.ToString("F");
            txtTaxRate.Text     = order.TaxRate.ToString("F");
            txtTaxAmount.Text   = order.TaxAmount.ToString("F");
            txtRepairTotal.Text = order.RepairTotal.ToString("F");
            txtRecommendations.Text = order.Recommendations;
    
            stmRepair.Close();
        }
    }
  26. On the form, click one of the multiline text boxes
  27. In the Properties window, click ScrollBars, then click the arrow of its field, and select Vertical
  28. On the form, click the other multiline text boxes
  29. In the Properties window, double-click ScrollBars until it displays Vertical
  30. To execute the application, press F5
  31. Create a repair order. Here is an example:
     
    College Park Auto Repair
  32. On the main menu of the form, click File -> Save As...
  33. Set the name to 100001 and click Save
  34. Create another order, calculate it and save it
  35. Try opening a previously saved order
  36. Close the form and return to your programming environment

Home Copyright © 2010-2020, FunctionX