Fundamentals of Record Maintenance

Introduction

Record maintenance consists of locating a value or a record, changing a value or a record, or deleting a value or a record. To assist you with this, the various classes of the System.Data namespace are equipped with many useful methods.

ApplicationPractical Learning: Introducing Tables Columns

  1. Start Microsoft Visual Studio
  2. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  3. In the middle frame of the New Object dialog box, make sure ASP.NET Web Application (.NET Framework) is selected.
    Change the project Name to GasUtilityCompany1
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, in the templates list, click the MVC icon and click OK
  6. In the Solution Explorer, right-click GasUtilityCompany1 -> Add -> New Folder
  7. Type GasDistribution and press Enter
  8. In the Solution Explorer, right-click GasUtilityCompany1 -> Add -> New Folder
  9. Type Images and press Enter
  10. Save the following image to your computer, then copy and paste it in the Image folder of the project:

    Gas Utility Company - Logo

  11. In the Solution Explorer, right-click Content -> Style Sheet
  12. Type GasUtilityCompany as the name of the file, and press Enter
  13. Add the following styles to the file:
    body {
        padding-top: 150px;
        background-color: #EEEEEE;
    }
    
    .bold              { font-weight:      600;             }
    .small             { width:            80px;            }
    .medium            { width:            120px;           }
    .large             { width:            175px;           }
    .sub-title         { border-bottom:    1px solid black; }
    #top-banner        { top:              0;
                         left:             0;
                         right:            0;
                         width:            100%;
                         bottom:           auto;
                         position:         fixed;
                         height:           5.75em;
                         background-color: #192E46;         }
    #bottom-banner     { left:             0;
                         right:            0;
                         bottom:           0;
                         top:              auto;
                         width:            100%;
                         position:         fixed;
                         height:           4.15em;
                         background-color: #003366;
                         border-top:       5pt solid black; }
    #copyright         { margin-top:       1em;
                         font-size:        1.15em;
                         text-align:       center;
                         line-height:      1.15em;
                         color:            lightcyan;         }
    .utility-container { margin:           auto;
                         width:            400px;             }
    .body-holder       { margin:           auto;
                         width:            800px;             }
    .centralizer       { margin:           auto;
                         width:            700px;             }
    .col-md-3          { border-radius:    6px;
                         padding-top:      10px;
                         padding-bottom:   10px;
                         background-color: #800000;
                         border:           1px solid #000000; }
    .jumbotron         { padding-top:      3px;
                         border-radius:    10px;
                         background-color: #f1ddca;           }
    .jumbotron h1      { font-size:        43px;
                         color:            #800000;           }
    .lead              { margin-bottom:    0;                 }
    .topic             { float:            left;              }
    .topic a:link, .topic a:active,
    .topic a:visited, .topic a:hover {
                         height:           32px;
                         font-size:        12pt;
                         line-height:      26px;
                         margin-left:     -10px;
                         padding-left:     20px;
                         text-decoration:  none;
                         display:          inline-block;
                         font-family:      'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    .topic, .topic a:link, .topic a:active,
    .topic a:visited, .topic a:hover { width: 190px;          }
    .topic a:link      { color:            #FFFF00;           }
    .topic a:active    { color:            #CC99FF;           }
    .topic a:visited   { color:            #FFCC99;           }
    .topic a:hover     { color:            #FFFFFF;
                         background-color: #ff6a00;
                         display:          inline-block;
                         outline:          1pt solid #CCFF33; }
    .navbar            { border-bottom:    5px solid navy;
                         border-top:      5px solid #faf76f;  }
    .navbar-inverse    { background-color: orange;
                         border-color:     #080808;           }
    .navbar-fixed-top  { top:              80px;              }
    .navbar-inverse .navbar-nav > li > a,
    .navbar-inverse .navbar-nav > li > a:link {
                         color:            #faf76f;
                         background-color: transparent;       }
    .navbar-inverse .navbar-nav > li > a:hover,
    .navbar-inverse .navbar-nav > li > a:focus {
                         color:            orange;
                         background-color: #faf76f;           }
    .common-font       { font-family: Garamond, Georgia, 'Times New Roman', serif; }
  14. In the Solution Explorer, under Views, expand App_Start and double-click BundleConfig.cs to open it
  15. Change the document as follows:
    using System.Web.Optimization;
    
    namespace GasUtilityCompany1
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/GasUtilityCompany.css"));
            }
        }
    }
  16. In the Solution Explorer, under Views, right-click Shared -> Add -> New Item...
  17. In the left frame of the Add New Item dialog box, under Visual C# and under Web, click Razor
  18. In the middle frame, click Layout Page (Razor v3)
  19. Set the Name to _Arrangement
  20. Press Enter
  21. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Gas Utility Company :: @Page.Title</title>
        @RenderSection("head", required: false)
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header id="top-banner">
            <p class="text-center"><img src="~/Images/guc.png" alt="Gas Utility Company" width="649" height="74" /></p>
        </header>
    
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="centralizer">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                    </div>
                    <div class="navbar-collapse collapse">
                        <ul class="nav navbar-nav">
                            <li>@Html.ActionLink("GUC Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("Gas Meters", "Index", "GasMeters")</li>
                            <li>@Html.ActionLink("Customers", "Index", "Customers")</li>
                            <li>@Html.ActionLink("Gas Bills", "Index", "GasBills")</li>
                            <li>@Html.ActionLink("Payments", "Index", "Payments")</li>
                            <li>@Html.ActionLink("Community", "Index", "Home")</li>
                            <li>@Html.ActionLink("Careers", "Index", "Home")</li>
                            <li>@Html.ActionLink("About GUC", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    
        <div class="body-holder">
            @RenderBody()
        </div>
    
        <hr />
    
        <footer id="bottom-banner">
            <p id="copyright">&copy; @DateTime.Now.Year - Gas Utility Company</p>
        </footer>
    </body>
    </html>
  22. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  23. In the Add Scaffold dialog box, click MVC 5 Controller With Read/Write Actions
  24. Click Add
  25. Type GasMeters to get GasMetersController
  26. Press Enter
  27. Change the document as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasDistribution2.Controllers
    {
        public class GasMetersController : Controller
        {
            private readonly DataColumn dcMake;
            private readonly DataColumn dcModel;
            private readonly DataColumn dcGasMeterID;
            private readonly DataColumn dcMeterNumber;
            private readonly DataColumn dcCounterValue;
            private readonly DataColumn dcMeterReadingDate;
    
            public DataTable dtGasMeters;
            public DataSet dsGasMeters;
    
            public GasMetersController()
            {
                dcGasMeterID = new DataColumn("gas-meter-id");
                dcGasMeterID.AutoIncrement = true;
                dcGasMeterID.AutoIncrementSeed = 1;
                dcGasMeterID.AutoIncrementStep = 1;
    
                dcMeterNumber = new DataColumn("meter-number");
                dcMeterNumber.Unique = true;
                dcMeterNumber.DataType = Type.GetType("System.String");
    
                dcMake = new DataColumn("make");
                dcMake.DataType = Type.GetType("System.String");
    
                dcModel = new DataColumn("model");
                dcModel.DataType = Type.GetType("System.String");
    
                dcMeterReadingDate = new DataColumn("meter-reading-date", Type.GetType("System.DateTime"));
    
                dcCounterValue = new DataColumn("counter-value");
                dcCounterValue.DataType = Type.GetType("System.Int32");
    
                dtGasMeters = new DataTable("gas-meter");
    
                dtGasMeters.Columns.Add(dcGasMeterID);
                dtGasMeters.Columns.Add(dcMeterNumber);
                dtGasMeters.Columns.Add(dcMake);
                dtGasMeters.Columns.Add(dcModel);
                dtGasMeters.Columns.Add(dcMeterReadingDate);
                dtGasMeters.Columns.Add(dcCounterValue);
    
                dsGasMeters = new DataSet("gas-meters");
                dsGasMeters.Tables.Add(dtGasMeters);
            }
    
            // GET: GasMeters
            public ActionResult Index()
            {
                return View();
            }
    
            . . . No Change
    
        }
    }
  28. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  29. In the left frame of the Add Scaffold dialog box, under Common, click MVC and, in the middle frame, click MVC 5 Controller With Read/Write Actions

    Add Scaffold

  30. Press Enter
  31. Type Customers to get CustomersController
  32. Click Add
  33. Change the document as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany10.Controllers
    {
        public class CustomersController : Controller
        {
            private readonly DataColumn dcCity;
            private readonly DataColumn dcState;
            private readonly DataColumn dcCounty;
            private readonly DataColumn dcZIPCode;
            private readonly DataColumn dcAddress;
            private readonly DataColumn dcLastName;
            private readonly DataColumn dcFirstName;
            private readonly DataColumn dcCustomerID;
            private readonly DataColumn dcMeterNumber;
            private readonly DataColumn dcAccountNumber;
    
            public DataTable dtCustomers;
            private DataSet dsCustomers;
    
            public CustomersController()
            {
                dcCustomerID = new DataColumn("customer-id")
                {
                    AutoIncrement = true,
                    AutoIncrementSeed = 1,
                    AutoIncrementStep = 1
                };
    
                dcCity = new DataColumn("city", Type.GetType("System.String"));
                dcState = new DataColumn("state", Type.GetType("System.String"));
                dcCounty = new DataColumn("county", Type.GetType("System.String"));
                dcAddress = new DataColumn("address", Type.GetType("System.String"));
                dcZIPCode = new DataColumn("zip-code", Type.GetType("System.String"));
                dcLastName = new DataColumn("last-name", Type.GetType("System.String"));
                dcFirstName = new DataColumn("first-name", Type.GetType("System.String"));
                dcMeterNumber = new DataColumn("meter-number", Type.GetType("System.String"));
                dcAccountNumber = new DataColumn("account-number", Type.GetType("System.String"))
                {
                    Unique = true
                };
    
                dtCustomers = new DataTable("customer");
    
                dtCustomers.Columns.Add(dcCustomerID);
                dtCustomers.Columns.Add(dcAccountNumber);
                dtCustomers.Columns.Add(dcMeterNumber);
                dtCustomers.Columns.Add(dcFirstName);
                dtCustomers.Columns.Add(dcLastName);
                dtCustomers.Columns.Add(dcAddress);
                dtCustomers.Columns.Add(dcCity);
                dtCustomers.Columns.Add(dcCounty);
                dtCustomers.Columns.Add(dcState);
                dtCustomers.Columns.Add(dcZIPCode);
    
                dsCustomers = new DataSet("customers");
                dsCustomers.Tables.Add(dtCustomers);
            }
    
            // GET: Customers
            public ActionResult Index()
            {
                return View();
            }
    
            . . . No Change
        }
    }
  34. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  35. Make sure MVC 5 Controller With Read/Write Actions is selected. Click Add
  36. Type GasBills to get GasBillsController
  37. Click Add
  38. Create a data set as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany10.Controllers
    {
        public class GasBillsController : Controller
        {
            private readonly DataColumn dcGasBillID;
            private readonly DataColumn dcAmountDue;
            private readonly DataColumn dcStateTaxes;
            private readonly DataColumn dcLocalTaxes;
            private readonly DataColumn dcConsumption;
            private readonly DataColumn dcBillingDays;
            private readonly DataColumn dcTotalTherms;
            private readonly DataColumn dcOver50Therms;
            private readonly DataColumn dcTotalCharges;
            private readonly DataColumn dcAccountNumber;
            private readonly DataColumn dcFirst50Therms;
            private readonly DataColumn dcDeliveryTotal;
            private readonly DataColumn dcLateAmountDue;
            private readonly DataColumn dcPaymentDueDate;
            private readonly DataColumn dcCounterReadingEnd;
            private readonly DataColumn dcCounterReadingStart;
            private readonly DataColumn dcMeterReadingEndDate;
            private readonly DataColumn dcEnvironmentalCharges;
            private readonly DataColumn dcMeterReadingStartDate;
            private readonly DataColumn dcTransportationCharges;
            private readonly DataColumn dcDistributionAdjustment;
    
            public DataTable dtGasBills;
            private DataSet dsGasBills;
    
            public GasBillsController()
            {
                dcGasBillID = new DataColumn("gas-bill-id")
                {
                    AutoIncrement = true,
                    AutoIncrementSeed = 1,
                    AutoIncrementStep = 1
                };
    
                dcAmountDue = new DataColumn("amount-due", Type.GetType("System.Decimal"));
                dcConsumption = new DataColumn("consumption", Type.GetType("System.Int32"));
                dcBillingDays = new DataColumn("billing-days", Type.GetType("System.Int32"));
                dcLocalTaxes = new DataColumn("local-taxes", Type.GetType("System.Decimal"));
                dcStateTaxes = new DataColumn("state-taxes", Type.GetType("System.Decimal"));
                dcTotalTherms = new DataColumn("total-therms", Type.GetType("System.String"));
                dcTotalCharges = new DataColumn("total-charges", Type.GetType("System.Decimal"));
                dcAccountNumber = new DataColumn("account-number", Type.GetType("System.String"));
                dcOver50Therms = new DataColumn("over-50-therms", Type.GetType("System.Decimal"));
                dcDeliveryTotal = new DataColumn("delivery-total", Type.GetType("System.Decimal"));
                dcFirst50Therms = new DataColumn("first-50-therms", Type.GetType("System.Decimal"));
                dcLateAmountDue = new DataColumn("late-amount-due", Type.GetType("System.Decimal"));
                dcPaymentDueDate = new DataColumn("payment-due-date", Type.GetType("System.DateTime"));
                dcCounterReadingEnd = new DataColumn("counter-reading-end", Type.GetType("System.Int32"));
                dcCounterReadingStart = new DataColumn("counter-reading-start", Type.GetType("System.Int32"));
                dcEnvironmentalCharges = new DataColumn("environmental-charges", Type.GetType("System.Decimal"));
                dcMeterReadingEndDate = new DataColumn("meter-reading-end-date", Type.GetType("System.DateTime"));
                dcTransportationCharges = new DataColumn("transportation-charges", Type.GetType("System.Decimal"));
                dcDistributionAdjustment = new DataColumn("distribution-adjustment", Type.GetType("System.Decimal"));
                dcMeterReadingStartDate = new DataColumn("meter-reading-start-date", Type.GetType("System.DateTime"));
    
                dtGasBills = new DataTable("gas-bill");
    
                dtGasBills.Columns.Add(dcGasBillID);
                dtGasBills.Columns.Add(dcAccountNumber);
                dtGasBills.Columns.Add(dcMeterReadingStartDate);
                dtGasBills.Columns.Add(dcMeterReadingEndDate);
                dtGasBills.Columns.Add(dcBillingDays);
                dtGasBills.Columns.Add(dcCounterReadingStart);
                dtGasBills.Columns.Add(dcCounterReadingEnd);
                dtGasBills.Columns.Add(dcConsumption);
                dtGasBills.Columns.Add(dcTotalTherms);
                dtGasBills.Columns.Add(dcTransportationCharges);
                dtGasBills.Columns.Add(dcFirst50Therms);
                dtGasBills.Columns.Add(dcOver50Therms);
                dtGasBills.Columns.Add(dcDeliveryTotal);
                dtGasBills.Columns.Add(dcDistributionAdjustment);
                dtGasBills.Columns.Add(dcEnvironmentalCharges);
                dtGasBills.Columns.Add(dcTotalCharges);
                dtGasBills.Columns.Add(dcLocalTaxes);
                dtGasBills.Columns.Add(dcStateTaxes);
                dtGasBills.Columns.Add(dcPaymentDueDate);
                dtGasBills.Columns.Add(dcAmountDue);
                dtGasBills.Columns.Add(dcLateAmountDue);
    
                dsGasBills = new DataSet("gas-bills");
                dsGasBills.Tables.Add(dtGasBills);
            }
    
            // GET: GasBills
            public ActionResult Index()
            {
                return View();
            }
    
            . . . No Change
        }
    }
  39. In the Solution Explorer, right-click Controllers -> Add -> Add Scaffolded Item...
  40. Make sure MVC 5 Controller With Read/Write Actions is selected. Click Add
  41. Type Payments to get PaymentsController
  42. Click Add
  43. Create a data set as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class PaymentsController : Controller
        {
            private readonly DataColumn dcGasBillID;
            private readonly DataColumn dcPaymentID;
            private readonly DataColumn dcPaymentDate;
            private readonly DataColumn dcPaymentAmount;
            private readonly DataColumn dcPaymentStatus;
    
            private DataTable dtPayments;
            private DataSet   dsPayments;
    
            public PaymentsController()
            {
                dcPaymentID = new DataColumn("payment-id")
                {
                    AutoIncrement = true,
                    AutoIncrementSeed = 1,
                    AutoIncrementStep = 1
                };
    
                dcPaymentStatus = new DataColumn("payment-status")
                {
                    DataType = Type.GetType("System.String")
                };
                dcGasBillID     = new DataColumn("gas-bill-id", Type.GetType("System.Int32"));
                dcPaymentDate   = new DataColumn("payment-date", Type.GetType("System.DateTime"));
                dcPaymentAmount = new DataColumn("payment-amount", Type.GetType("System.Decimal"));
    
                dtPayments = new DataTable("payment");
                dtPayments.Columns.Add(dcPaymentID);
                dtPayments.Columns.Add(dcPaymentDate);
                dtPayments.Columns.Add(dcGasBillID);
                dtPayments.Columns.Add(dcPaymentAmount);
                dtPayments.Columns.Add(dcPaymentStatus);
    
                dsPayments = new DataSet("payments");
                dsPayments.Tables.Add(dtPayments);
            }
           
            . . . No Change
        }
    }

Creating a Record

The DataSet supports all regular operations of a database. The primary operation consists of creating records. This consists of creating a row, adding it to a data set, and then saving the data set.

Practical LearningPractical Learning: Creating Records

  1. Click the GasMetersController.cs tab to access the controller
  2. In the GasMetersController class, change the second Create() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasMetersController : Controller
        {
            . . . No Change
    
            // GET: GasMeters/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: GasMeters/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    if (!string.IsNullOrEmpty(collection["MeterNumber"]))
                    {
                        if (System.IO.File.Exists(strGasMetersFile))
                        {
                            using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                dsGasMeters.ReadXml(fsGasMeters);
                            }
                        }
    
                        DataRow drGasMeter = dtGasMeters.NewRow();
    
                        drGasMeter["meter-number"]       = collection["MeterNumber"];
                        drGasMeter["make"]               = collection["Make"];
                        drGasMeter["model"]              = collection["Model"];
                        drGasMeter["meter-reading-date"] = collection["MeterReadingDate"];
                        drGasMeter["counter-value"]      = collection["CounterValue"];
    
                        dtGasMeters.Rows.Add(drGasMeter);
    
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            dsGasMeters.WriteXml(fsGasMeters);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  3. In the class, right-click one of the Create() methods and click Add View...
  4. In the Add View dialog box, make sure the View Name text box is displaying Create.
    Click the Browse button Browse Button - Use A Layout Page on the right side of the Use A Layout Page text box
  5. In the tree list of the Select A Layout Page dialog box, expand Views and click Shared
  6. In the Contents Of Folder list box, make sure _Arrangement.cshtml is selected (if not, click it):

    Select a Layout Page

    Click OK

    Select a Layout Page

  7. Click Add
  8. Create a form as follows:
    @{
        ViewBag.Title = "New Gas Meter";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">New Gas Meter</h2>
    
    @using (Html.BeginForm())
    {
        <div class="utility-container">
            <table class="common-font">
                <tr>
                    <td class="medium bold">Meter #:</td>
                    <td>@Html.TextBox("MeterNumber")</td>
                </tr>
                <tr>
                    <td class="bold">Make:</td>
                    <td>@Html.TextBox("Make")</td>
                </tr>
                <tr>
                    <td class="bold">Model</td>
                    <td>@Html.TextBox("Model")</td>
                </tr>
                <tr>
                    <td class="large bold">Meter Reading Date:</td>
                    <td>
                        @Html.TextBox("MeterReadingDate", null,
                                  htmlAttributes: new { type = "date" })
                    </td>
                </tr>
    
                <tr>
                    <td class="bold">Counter Value:</td>
                    <td>@Html.TextBox("CounterValue")</td>
                </tr>
            </table>
            <hr />
            <p class="text-center">
                <a href="/GasMeters/Index" class="btn btn-warning">Gas Meters</a> 
                <input type="submit" name="btnCreateGasMeter"
                       value="Create Gas Meter" class="btn btn-warning" />
            </p>
        </div>
    }
  9. Click the CustomersController.cs tab to access the controller
  10. Change the second Create() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class CustomersController : Controller
        {
    
            . . . No Change
    
            // GET: Customers/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Customers/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    GasMetersController gasMtrCtrlr = new GasMetersController();
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        if (System.IO.File.Exists(strCustomersFile))
                        {
                            using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                dsCustomers.ReadXml(fsCustomers);
                            }
                        }
    
                        DataRow drCustomer = dtCustomers.NewRow();
    
                        drCustomer["account-number"] = collection["AccountNumber"];
                        drCustomer["meter-number"]   = collection["MeterNumber"];
                        drCustomer["first-name"]     = collection["FirstName"];
                        drCustomer["last-name"]      = collection["LastName"];
                        drCustomer["address"]        = collection["Address"];
                        drCustomer["city"]           = collection["City"];
                        drCustomer["county"]         = collection["County"];
                        drCustomer["state"]          = collection["State"];
                        drCustomer["zip-code"]       = collection["ZIPCode"];
    
                        dtCustomers.Rows.Add(drCustomer);
    
                        using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                        {
                            dsCustomers.WriteXml(fsCustomers);
                        }
                    }
    
                    // Return the user to the list of customers
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  11. In the Solution Explorer, under Controllers, double-click PaymentsController.cs
  12. Implement the second Create() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class PaymentsController : Controller
        {
            
            . . . No Change
    
            // GET: Payments/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Payments/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                    if (System.IO.File.Exists(strPaymentsFile))
                    {
                        using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsPayments.ReadXml(fsPayments);
                        }
                    }
                        
                    DataRow drPayment = dtPayments.NewRow();
    
                    drPayment["payment-date"]   = collection["PaymentDate"];
                    drPayment["gas-bill-id"]    = collection["GasBillID"];
                    drPayment["payment-amount"] = collection["PaymentAmount"];
                    drPayment["payment-status"] = collection["PaymentStatus"];
    
                    dtPayments.Rows.Add(drPayment);
    
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        dsPayments.WriteXml(fsPayments);
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
                
        }
    }
  13. In the class, right-click one of the Create() methods and click Add View...
  14. Make sure the View Name text box displays Create.
    Make sure the Use A Layout Page text box is showing ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  15. Create the form as follows:
    @{
        ViewBag.Title = "Create Bill Payment";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        System.Collections.Generic.List<SelectListItem> categories = new List<SelectListItem>();
        categories.Add(new SelectListItem { Text = "On Time",      Value = "On Time" });
        categories.Add(new SelectListItem { Text = "Late Payment", Value = "Late Payment" });
    }
    
    <h2 class="text-center common-font bold">Make Gas Bill Payment</h2>
    
    @using (Html.BeginForm())
    {
        <div class="utility-container">
            <table class="common-font">
                <tr>
                    <td class="medium bold">Payment Date:</td>
                    <td>@Html.TextBox("PaymentDate", null,
                                      htmlAttributes: new { type = "date" })
                </td>
            </tr>
            <tr>
                <td class="bold">Gas Bill ID:</td>
                <td>@Html.TextBox("GasBillID")</td>
            </tr>
            <tr>
                <td class="bold">Payment Amount:</td>
                <td>@Html.TextBox("PaymentAmount")</td>
            </tr>
            <tr>
                <td class="large bold">Payment Status:</td>
                <td>@Html.DropDownList("PaymentStatus", categories)</td>
            </tr>
        </table>
        <hr />
        <p class="text-center">
            <a href="/Payments/Index" class="btn btn-warning">Gas Bills Payments</a> 
            <input type="submit" name="btnCreatePayment"
                   value="Make Gas Bill Payment" class="btn btn-warning" />
    </p>
    </div>
    }

Inserting a Record

Inserting a First Record

Besides the different techniques of creating records on a table, the DataRowCollection provides a method named InsertAt. Its syntax is:

public void InsertAt(DataRow row, int pos);

The first argument is the collection of values to be added as the new record of the table. The pos argument is the position that the new record should assume in the table. If the position is set to 0, the record would be added as the first. Here are examples:

<!DOCTYPE html>
<html>
<head>
    <title>Chemistry: Periodic Table</title>
</head>
<body>
    <h1>Chemistry</h1>
    <h2>Periodic Table</h2>

    @{
        System.Data.DataTable dtElements = new System.Data.DataTable("element");

        dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
        dtElements.Columns.Add("symbol", Type.GetType("System.String"));
        dtElements.Columns.Add("element-name", Type.GetType("System.String"));
        dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

        System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
        dsChemistry.Tables.Add(dtElements);

        System.Data.DataRow drElement = dtElements.NewRow();

        drElement[0] = 3;
        drElement[1] = "Li";
        drElement[2] = "Lithium";
        drElement[3] = 6.938f;
        dtElements.Rows.InsertAt(drElement, 0);

        drElement = dtElements.NewRow();

        drElement[0] = 1;
        drElement[1] = "H";
        drElement[2] = "Hydrogen";
        drElement[3] = 1.008f;
        dtElements.Rows.InsertAt(drElement, 0);
    }

    @{
        int i = 0;

        <table border="5">
            <tr>
                <td><b>Atomic #</b></td>
                <td><b>Symbol</b></td>
                <td><b>Element Name</b></td>
                <td><b>Atomic Weight</b></td>
            </tr>
            @while (i < dtElements.Rows.Count)
            {
                drElement = dtElements.Rows[i];

                <tr>
                    <td>@drElement[0]</td>
                    <td>@drElement[1]</td>
                    <td>@drElement[2]</td>
                    <td>@drElement[3]</td>
                </tr>

                i++;
            }
        </table>
    }
</body>
</html>

This would produce:

Students

When a new record has just been created, its status is changed using an appropriate member of the DataRowState enumeration. In this case, the record would be flagged as RowState.Added. This is done automatically, to find out whether a certain record currently has the RowState.Added value, you can check the value of its RowState property.

After creating a new record, to let you set the flag as a new record, the DataRow class is equipped with a method named SetAdded. Its syntax is:

public void SetAdded();

Inserting a Last Record

To create a record as the last, set the position of the DataRowCollection.InsertAt() method to a value equal to, or higher than, the total number of items in the collection. This means that, when inserting a record, if the position is equal to or higher than the total number of records (DataRowCollection.Count), the new record would be added as the last record to the table (in both cases, the compiler would not throw an exception). Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry: Periodic Table</title>
</head>
<body>
<h1>Chemistry</h1>
<h2>Periodic Table</h2>

@{
    System.Data.DataTable dtElements = new System.Data.DataTable("element");

    dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
    dtElements.Columns.Add("symbol", Type.GetType("System.String"));
    dtElements.Columns.Add("element-name", Type.GetType("System.String"));
    dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

    System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
    dsChemistry.Tables.Add(dtElements);

    System.Data.DataRow drElement = dtElements.NewRow();

    drElement[0] = 3;
    drElement[1] = "Li";
    drElement[2] = "Lithium";
    drElement[3] = 6.938f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 1;
    drElement[1] = "H";
    drElement[2] = "Hydrogen";
    drElement[3] = 1.008f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 4;
    drElement[1] = "Be";
    drElement[2] = "Beryllium";
    drElement[3] = 9.0121831f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();

    drElement[0] = 5;
    drElement[1] = "B";
    drElement[2] = "Boron";
    drElement[3] = 10.806f;
    dtElements.Rows.InsertAt(drElement, 500);
}

@{
    int i = 0;
    
    <table border="5">
        <tr>
            <td><b>Atomic #</b></td>
            <td><b>Symbol</b></td>
            <td><b>Element Name</b></td>
            <td><b>Atomic Weight</b></td>
        </tr>
    @while (i < dtElements.Rows.Count)
    {
        drElement = dtElements.Rows[i];
        
        <tr>
            <td>@drElement[0]</td>
            <td>@drElement[1]</td>
            <td>@drElement[2]</td>
            <td>@drElement[3]</td>
        </tr>

        i++;
    }
    </table>
}
</body>
</html>

This would produce:

Students

Inserting Between Records

You can insert a record between two existing records. To do this, pass the position of the DataRowCollection.InsertAt() method to the index you want. This would be a value to the actual array index plus 1. For example, if you want to insert an item in the second position, you would pass the position as 1. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry: Periodic Table</title>
</head>
<body>
<h1>Chemistry</h1>
<h2>Periodic Table</h2>

@{
    System.Data.DataTable dtElements = new System.Data.DataTable("element");

    dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
    dtElements.Columns.Add("symbol", Type.GetType("System.String"));
    dtElements.Columns.Add("element-name", Type.GetType("System.String"));
    dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

    System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
    dsChemistry.Tables.Add(dtElements);

    System.Data.DataRow drElement = dtElements.NewRow();

    drElement[0] = 3;
    drElement[1] = "Li";
    drElement[2] = "Lithium";
    drElement[3] = 6.938f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 1;
    drElement[1] = "H";
    drElement[2] = "Hydrogen";
    drElement[3] = 1.008f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 4;
    drElement[1] = "Be";
    drElement[2] = "Beryllium";
    drElement[3] = 9.0121831f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();

    drElement[0] = 5;
    drElement[1] = "B";
    drElement[2] = "Boron";
    drElement[3] = 10.806f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();  drElement[0] = 2;

    drElement[1] = "He";
    drElement[2] = "Helium";
    drElement[3] = 4.002602f;
    dtElements.Rows.InsertAt(drElement, 1);
}

@{
    int i = 0;

    <table border="5">
        <tr>
            <td><b>Atomic #</b></td>
            <td><b>Symbol</b></td>
            <td><b>Element Name</b></td>
            <td><b>Atomic Weight</b></td>
        </tr>
    @while (i < dtElements.Rows.Count)
    {
        drElement = dtElements.Rows[i];
        
        <tr>
            <td>@drElement[0]</td>
            <td>@drElement[1]</td>
            <td>@drElement[2]</td>
            <td>@drElement[3]</td>
        </tr>

        i++;
    }
    </table>
}
</body>
</html>

This would produce:

Students

There are some rules when calling the DataRowCollection.InsertAt() method. If the table does not have a column whose value is incremental (where a DataColumn.AutoIncrement is set to true), if you specify a position between 0 and the maximum number of records, the new record can be inserted between two existing records.

public void SetAdded();

Reading Records

An important operation performed on a database is to get the records of a table. In a data set, the records are held by a DataTable object in its Rows properties, which is a collection.

Practical LearningPractical Learning: Reading Records

  1. Click the GasMetersController.cs tab to access the class
  2. Implement the Index() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasMetersController : Controller
        {
            . . . No Change
    
            public GasMetersController()
            {
                . . . No Change
            }
    
            // GET: GasMeters
            public ActionResult Index()
            {
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasMeters.ReadXml(fsGasMeters);
                    }
                }
    
                ViewBag.GasMeters = dsGasMeters.Tables[0].Rows;
    
                return View();
            }
    
            . . . No Change
        }
    }
  3. In the class, right-click inside the Index() method and click Add View...
  4. Make sure the View Name text box displays Index.
    Make sure the Use A Layout Page text box is showing ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  5. Change the webpage as follows:
    @{
        ViewBag.Title = "Gas Meters";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Gas Meters</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Gas Meter ID</th>
            <th class="bold">Meter #</th>
            <th class="bold">Make</th>
            <th class="bold">Model</th>
            <th class="bold">Counter Reading Date</th>
            <th class="bold text-center">Counter Value</th>
            <th>@Html.ActionLink("New Gas Meter", "Create")</th>
        </tr>
        @foreach (System.Data.DataRow drGasMeter in ViewBag.GasMeters)
        {
            string mrd = DateTime.Parse(drGasMeter["meter-reading-date"].ToString()).ToShortDateString();
    
            <tr>
                <td class="text-center">@drGasMeter["gas-meter-id"].ToString()</td>
                <td>@drGasMeter["meter-number"].ToString()</td>
                <td>@drGasMeter["make"].ToString()</td>
                <td>@drGasMeter["model"].ToString()</td>
                <td class="text-center">@mrd</td>
                <td class="text-center">@drGasMeter["counter-value"].ToString()</td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = @drGasMeter["gas-meter-id"].ToString() }) |
                    @Html.ActionLink("Details", "Details", new { id = @drGasMeter["gas-meter-id"].ToString() }) |
                    @Html.ActionLink("Delete", "Delete", new { id = @drGasMeter["gas-meter-id"].ToString() })
                </td>
            </tr>
        }
    </table>
  6. Click the CustomersController.cs tab and implement the Index() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class CustomersController : Controller
        {
            . . . No Change
    
            // GET: Customers
            public ActionResult Index()
            {
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsCustomers);
                    }
                }
    
                ViewBag.Customers = dsCustomers.Tables[0].Rows;
                return View();
            }
    
            . . . No Change
        }
    }
  7. In the class, right-click below the Index() line and click Add View...
  8. Make sure the View Name text box displays Index.
    Make sure the Use A Layout Page text box shows ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  9. Create the webpage as follows:
    @{
        ViewBag.Title = "Customers";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Customers</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Customer ID</th>
            <th class="bold text-center">Account #</th>
            <th class="bold">Meter #</th>
            <th class="bold">First Name</th>
            <th class="bold">Last Name</th>
            <th class="bold">Address</th>
            <th class="bold">City</th>
            <th class="bold">County</th>
            <th class="bold">State</th>
            <th class="bold">ZIP-Code</th>
            <th>@Html.ActionLink("New Customer Account", "Create")</th>
        </tr>
        @foreach (System.Data.DataRow drCustomer in ViewBag.Customers)
        {
            <tr>
                <td class="text-center">@drCustomer["customer-id"].ToString()</td>
                <td>@drCustomer["account-number"].ToString()</td>
                <td>@drCustomer["meter-number"].ToString()</td>
                <td>@drCustomer["first-name"].ToString()</td>
                <td>@drCustomer["last-name"].ToString()</td>
                <td>@drCustomer["address"].ToString()</td>
                <td>@drCustomer["city"].ToString()</td>
                <td>@drCustomer["county"].ToString()</td>
                <td>@drCustomer["state"].ToString()</td>
                <td>@drCustomer["zip-code"].ToString()</td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = @drCustomer["customer-id"].ToString() }) |
                    @Html.ActionLink("Details", "Details", new { id = @drCustomer["customer-id"].ToString() }) |
                    @Html.ActionLink("Delete", "Delete", new { id = @drCustomer["customer-id"].ToString() })
                </td>
            </tr>
        }
    </table>
  10. In the Solution Explorer, under Controllers, double-click GasBillsControllers.cs and change its Index() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasBillsController : Controller
        {
            . . . No Change
    
            // GET: GasBills
            public ActionResult Index()
            {
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
                    }
                }
    
                ViewBag.GasBills = dsGasBills.Tables[0].Rows;
                return View();
            }
    
            . . . No Change
        }
    }
  11. In the class, right-click Index() and click Add View...
  12. Make sure the View Name text box displays Index.
    Make sure the Use A Layout Page text box shows ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  13. Create the webpage as follows:
    @{
        ViewBag.Title = "Gas Bills";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Gas Bills</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td colspan="3" class="bold text-center">Meter Reading</td>
            <td colspan="3" class="bold text-center">Counter Reading</td>
            <td colspan="5" class="bold text-center">Therms</td>
            <td colspan="3" class="bold text-center">Delivery Charges</td>
            <td colspan="2" class="bold text-center">Taxes</td>
            <td colspan="3" class="bold text-center">Payment</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <th class="bold text-center">Gas Bill ID</th>
            <th class="bold text-center">Account #</th>
            <th class="bold">Start Date</th>
            <th class="bold">End Date</th>
            <th class="bold">Days</th>
            <th class="bold">Start</th>
            <th class="bold">End</th>
            <th class="bold">Consumption</th>
            <th class="bold">Total Therms</th>
            <th class="bold">Transp</th>
            <th class="bold">1st 50</th>
            <th class="bold">Over 50</th>
            <th class="bold">Total</th>
            <th class="bold">Dist. Adjust.</th>
            <th class="bold">Environment</th>
            <th class="bold">Total Charges</th>
            <th class="bold">Local</th>
            <th class="bold">State</th>
            <th class="bold">Due Date</th>
            <th class="bold">Amount</th>
            <th class="bold">Late Amount</th>
            <th>@Html.ActionLink("New Customer Account", "Create")</th>
        </tr>
        @foreach (System.Data.DataRow drGasBill in ViewBag.GasBills)
        {
            string pdd  = DateTime.Parse(drGasBill["payment-due-date"].ToString()).ToShortDateString();
            string mred = DateTime.Parse(drGasBill["meter-reading-end-date"].ToString()).ToShortDateString();
            string mrsd = DateTime.Parse(drGasBill["meter-reading-start-date"].ToString()).ToShortDateString();
    
        <tr>
            <td class="text-center">@drGasBill["gas-bill-id"].ToString()</td>
            <td>@drGasBill["account-number"].ToString()</td>
            <td>@mrsd</td>
            <td>@mred</td>
            <td>@drGasBill["billing-days"].ToString()</td>
            <td>@drGasBill["counter-reading-start"].ToString()</td>
            <td>@drGasBill["counter-reading-end"].ToString()</td>
            <td>@drGasBill["consumption"].ToString()</td>
            <td>@drGasBill["total-therms"].ToString()</td>
            <td>@drGasBill["transportation-charges"].ToString()</td>
            <td>@drGasBill["first-50-therms"].ToString()</td>
            <td>@drGasBill["over-50-therms"].ToString()</td>
            <td>@drGasBill["delivery-total"].ToString()</td>
            <td>@drGasBill["distribution-adjustment"].ToString()</td>
            <td>@drGasBill["environmental-charges"].ToString()</td>
            <td>@drGasBill["total-charges"].ToString()</td>
            <td>@drGasBill["local-taxes"].ToString()</td>
            <td>@drGasBill["state-taxes"].ToString()</td>
            <td>@pdd</td>
            <td>@drGasBill["amount-due"].ToString()</td>
            <td>@drGasBill["late-amount-due"].ToString()</td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = @drGasBill["gas-bill-id"].ToString() }) |
                @Html.ActionLink("Details", "Details", new { id = @drGasBill["gas-bill-id"].ToString() }) |
                @Html.ActionLink("Delete", "Delete", new { id = @drGasBill["gas-bill-id"].ToString() })
            </td>
        </tr>
        }
    </table>
  14. In the Solution Explorer, under Controllers, double-click PaymentsController.cs and change the Index() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class PaymentsController : Controller
        {
           
            . . . No Change
    
            // GET: Payments
            public ActionResult Index()
            {
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
                
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
                    }
                }
    
                ViewBag.Payments = dsPayments.Tables[0].Rows;
                return View();
            }
    
            . . . No Change
        }
    }
  15. In the class, right-click Index() and click Add View...
  16. Make sure the View Name text box displays Index.
    Make sure the Use A Layout Page text box shows ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  17. Create the webpage as follows:
    @{
        ViewBag.Title = "Gas Bills Payments";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Gas Bills Payments</h2>
    
    <table class="table table-striped common-font">
        <tr class="text-center">
            <th class="bold">Payment ID</th>
            <th class="bold">Payment Date</th>
            <th class="bold">Gas Bill #</th>
            <th class="bold">Payment Amount</th>
            <th class="bold">payment-status</th>
            <th>@Html.ActionLink("New Gas Meter", "Create")</th>
        </tr>
        @foreach (System.Data.DataRow drPayment in ViewBag.Payments)
        {
            string pmtDate = DateTime.Parse(drPayment["payment-date"].ToString()).ToLongDateString();
    
        <tr class="text-center">
            <td>@drPayment["payment-id"].ToString()</td>
            <td>@pmtDate</td>
            <td>@drPayment["gas-bill-id"].ToString()</td>
            <td>@drPayment["payment-Amount"].ToString()</td>
            <td>@drPayment["payment-status"].ToString()</td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = @drPayment["payment-id"].ToString() }) |
                @Html.ActionLink("Details", "Details", new { id = @drPayment["payment-id"].ToString() }) |
                @Html.ActionLink("Delete", "Delete", new { id = @drPayment["payment-id"].ToString() })
            </td>
        </tr>
        }
    </table>
  18. In the Solution Explorer, expand Views and expand Shared
  19. Double-click _Layout.cshtml and change it as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gas Utility Company :: @ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header id="top-banner">
            <p class="text-center"><img src="~/Images/guc.png" alt="Gas Utility Company" width="649" height="74" /></p>
        </header>
    
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="centralizer">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                    </div>
                    <div class="navbar-collapse collapse">
                        <ul class="nav navbar-nav">
                            <li>@Html.ActionLink("GUC Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("Gas Meters", "Index", "GasMeters")</li>
                            <li>@Html.ActionLink("Customers", "Index", "Customers")</li>
                            <li>@Html.ActionLink("Gas Bills", "Index", "GasBills")</li>
                            <li>@Html.ActionLink("Payments", "Index", "Payments")</li>
                            <li>@Html.ActionLink("Community", "Index", "Home")</li>
                            <li>@Html.ActionLink("Careers", "Index", "Home")</li>
                            <li>@Html.ActionLink("About GUC", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    
        <div class="body-holder">
            <div class="col-md-3">
                <div class="topic">@Html.ActionLink("Safety", "Index", "Home")</div>
                <div class="topic">@Html.ActionLink("Outages", "Index", "Home")</div>
                <div class="topic">@Html.ActionLink("Commercial", "Index", "Home")</div>
                <div class="topic">@Html.ActionLink("Residential", "Index", "Home")</div>
                <div class="topic">@Html.ActionLink("Environment", "Index", "Home")</div>
                <div class="topic">@Html.ActionLink("Services/Appliances", "Index", "Home")</div>
                <div class="topic">@Html.ActionLink("Community Relations", "Index", "Home")</div>
            </div>
            <div class="col-md-9">
                @RenderBody()
            </div>
        </div>
    
        <hr />
    
        <footer id="bottom-banner">
            <p id="copyright">&copy; @DateTime.Now.Year - Gas Utility Company</p>
        </footer>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  20. To execute the application and test record creation, on the main menu, click Debug -> Start Without Debugging

    Data Sets Maintenance

  21. Click the Gas Meters Link:

    Data Sets Maintenance - Gas Meters

  22. Click the New Gas Meter link:

    Data Sets Maintenance - New Gas Meters

    Data Sets Maintenance - New Gas Meters

  23. Create some records as follows:
    Meter # Make Model Meter Reading Date Counter Value
    582741-38 Sinton International D-244 5/22/2017 138
    293847-27 Arc Metal LP2066 8/31/2017 6628
    928731-59 EnvioSmart 84-D9703 12/16/2016 8016
    797047-27 Archimeda LP2066 10/6/2015 725
    425837-14 EnvioSmart 28-G4428 1/8/2018 6114
    864085-92 Sinton International D-244 10/15/2014 226857
    8288-4837 Facial Recognition LWBG-2930 12/18/2018 10010

    Introduction to Maintenance of Data Sets

  24. Close the browser and return to your programming environment

Locating a Record

Most of the operations you want to perform on a record require that you identify the record you want to work on. To do this, you can use any of the techniques we saw already to locate a record.

Practical LearningPractical Learning: Finding a Record

  1. In the Solution Explorer, under Controllers, double-click GasMetersController.cs tab to access the class
  2. Implement the Details() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasMetersController : Controller
        {
    
            . . . No Change
    
            // GET: GasMeters/Details/5
            public ActionResult Details(int id)
            {
                // DataRow drCustomerMeter = null;
                DataRow drCustomerMeter = null;
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // Open the list of records and store them in a data set
                        dsGasMeters.ReadXml(fsGasMeters);
    
                        // Check each record
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            // Look for a Gas Meter ID that has the same value as the argument to the current method
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                // If you find such a record, get its reference
                                drCustomerMeter = drGasMeter;
                            }
                        }
                    }
                }
    
                // Send the record to the view
                ViewBag.GasMeter = drCustomerMeter;
    
                return View();
            }        
    
            . . . No Change
        }
    }
  3. In the class, right-click Details() and click Add View...
  4. Make sure the View Name text box is displaying Details.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  5. Change the webpage as follows:
    @{
        ViewBag.Title = "Gas Meter Details";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string mrd = DateTime.Parse(ViewBag.GasMeter["meter-reading-date"].ToString()).ToLongDateString();
    }
    
    <h2 class="text-center common-font bold">Gas Meter Details</h2>
    
    <hr />
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="medium bold">Gas Meter ID:</td>
                <td>@ViewBag.GasMeter["gas-meter-id"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Meter #:</td>
                <td>@ViewBag.GasMeter["meter-number"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Make:</td>
                <td>@ViewBag.GasMeter["make"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Model:</td>
                <td>@ViewBag.GasMeter["model"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Meter Reading Date:</td>
                <td>@mrd</td>
            </tr>
            <tr>
                <td class="bold">Counter Value:</td>
                <td>@ViewBag.GasMeter["counter-value"].ToString()</td>
            </tr>
        </table>
    </div>
    <hr color="black" />
    <p class="text-center">
        @Html.ActionLink("Edit/Update Gas Meter Information", "Edit",
                         new { id = @ViewBag.GasMeter["gas-meter-id"] }, null) ::
        @Html.ActionLink("Delete Gas Meter", "Delete",
                         new { id = @ViewBag.GasMeter["gas-meter-id"] }, null) ::
        @Html.ActionLink("Gas Meters", "Index")
    </p>
  6. In the Solution Explorer, under Controllers, double-click CustomersController.cs to access the document
  7. Implement the Details() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class CustomersController : Controller
        {
    
            . . . No Change
    
            // GET: Customers/Details/5
            public ActionResult Details(int id)
            {
                DataRow drCustomer = null;
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsGasMeters);
    
                        foreach (DataRow drClient in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drClient["customer-id"].ToString()) == id)
                            {
                                drCustomer = drClient;
                            }
                        }
                    }
                }
    
                ViewBag.Customer = drCustomer;
                return View();
            }
    
            . . . No Change
        }
    }
  8. In the class, right-click Details() and click Add View...
  9. Make sure the View Name text box is displaying Details.
    Make sure the Use A Layout Page text box has ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  10. Change the webpage as follows:
    @{
        ViewBag.Title = "Customer Account Details";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Customer Account Details</h2>
    
    <hr />
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="medium bold">Customer ID:</td>
                <td>@ViewBag.Customer["customer-id"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Account #:</td>
                <td>@ViewBag.Customer["account-number"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Meter #:</td>
                <td>@ViewBag.Customer["meter-number"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">First Name:</td>
                <td>@ViewBag.Customer["first-name"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Last Name:</td>
                <td>@ViewBag.Customer["last-name"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Address:</td>
                <td>@ViewBag.Customer["address"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">City:</td>
                <td>@ViewBag.Customer["city"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">County:</td>
                <td>@ViewBag.Customer["county"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">State:</td>
                <td>@ViewBag.Customer["state"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">ZIP-Code:</td>
                <td>@ViewBag.Customer["zip-code"].ToString()</td>
            </tr>
        </table>
    </div>
    <hr color="black" />
    <p class="text-center">
        @Html.ActionLink("Edit/Update Customer Account Details", "Edit",
                         new { id = @ViewBag.Customer["customer-id"] }, null) ::
        @Html.ActionLink("Delete Customer Account", "Delete",
                         new { id = @ViewBag.Customer["customer-id"] }, null) ::
        @Html.ActionLink("Customers Accounts", "Index")
    </p>
  11. Click the CustomersController.cs tab
  12. In the class, right-click one of the Create() methods and click Add View...
  13. Make sure the View Name text box displays Create.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  14. Create a form as follows:
    @{
        ViewBag.Title = "New Customer Account";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">New Customer Account</h2>
    
    @using (Html.BeginForm())
    {
        <div class="utility-container">
            <table class="common-font">
                <tr>
                    <td class="medium bold">Account #:</td>
                    <td>@Html.TextBox("AccountNumber")</td>
                </tr>
                <tr>
                    <td class="bold">Meter #:</td>
                    <td>
                        @Html.TextBox("MeterNumber", null,
                                  htmlAttributes: new { id = "meterNumber" })
                    </td>
                </tr>
                <tr>
                    <td class="bold">Meter Details:</td>
                    <td><span id="meterDetails"></span></td>
                </tr>
                <tr>
                    <td class="bold">First Name:</td>
                    <td>@Html.TextBox("FirstName")</td>
                </tr>
                <tr>
                    <td class="bold">Last Name:</td>
                    <td>@Html.TextBox("LastName")</td>
                </tr>
                <tr>
                    <td class="bold">Address:</td>
                    <td>@Html.TextBox("Address")</td>
                </tr>
                <tr>
                    <td class="bold">City:</td>
                    <td>@Html.TextBox("City")</td>
                </tr>
                <tr>
                    <td class="bold">County:</td>
                    <td>@Html.TextBox("County")</td>
                </tr>
                <tr>
                    <td class="bold">State:</td>
                    <td>@Html.TextBox("State")</td>
                </tr>
                <tr>
                    <td class="bold">ZIP-Code:</td>
                    <td>@Html.TextBox("ZIPCode")</td>
                </tr>
            </table>
            <hr />
            <p class="text-center">
                <a class="btn btn-warning" href="/Customers/Index">Customers Accounts</a> 
                <input type="submit" name="btnCreateCustomerAccount"
                       value="Create Customer Account" class="btn btn-warning" />
            </p>
        </div>
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#meterNumber").blur(function (event) {
                $.ajax({
                    method: "GET",
                    dataType: "xml",
                    url: "/GasDistribution/GasMeters.xml",
                    success: function (data) {
                        var gasMeters = $(data).find("gas-meter");
                        gasMeters.each(function () {
                            if ($(this).find("meter-number").text() === $("#meterNumber").val())
                                $("#meterDetails").text($(this).find("make").text() + " " + $(this).find("model").text());
                        }); // Each Gas Meter
                    } // Success
                }); // Ajax
            }); // Meter Number Lost Focus Event
        }); // Document.Ready
    </script>
  15. To execute the application, press Ctrl + F5:

    Data Set Maintenance - New Customer Account

  16. Enter the following values in the text boxes:
    Account #:  60-9720-824
    Meter #:    293847-27
    First Name: Jefferey
    Last Name:  Parriot
    Address:    688 Gorman St
    City:       Rockville
    County:     Montgomery
    State:      MD
    ZIP-Code:   20856

    Web API - Creating a Record

  17. Click the Save Customer Account button
  18. Close the browser and return to your programming environment
  19. In the Solution Explorer, under Controllers, right-click GasBillsController.cs and click Open
  20. Implement the Details() method as follows:
    using System;
    using System.Data;
    using System.IO;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany10.Controllers
    {
        public class GasBillsController : Controller
        {
            . . . No Change
    
            // GET: GasBills/Details/5
            public ActionResult Details(int id)
            {
                DataRow drGasBill = null;
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
    
                        foreach (DataRow drClient in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drClient["gas-bill-id"].ToString()) == id)
                            {
                                drGasBill = drClient;
                            }
                        }
                    }
                }
    
                ViewBag.Invoice = drGasBill;
                return View();
            }
    
            . . . No Change
        }
    }
  21. In the class, right-click any part of the code that was written and click Add View...
  22. Make sure the View Name text box displays Details.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  23. Change the webpage as follows:
    @{
        ViewBag.Title = "Details";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string pdd  = DateTime.Parse(ViewBag.Invoice["payment-due-date"].ToString()).ToLongDateString();
        string mred = DateTime.Parse(ViewBag.Invoice["meter-reading-end-date"].ToString()).ToLongDateString();
        string mrsd = DateTime.Parse(ViewBag.Invoice["meter-reading-start-date"].ToString()).ToLongDateString();
    }
    
    <h2 class="text-center common-font bold">Gas Bill Details</h2>
    
    <hr />
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="large bold">Gas Bill ID:</td>
                <td>@ViewBag.Invoice["gas-bill-id"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Account #:</td>
                <td>@ViewBag.Invoice["account-number"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Meter Reading Start Date:</td>
                <td>@mrsd</td>
            </tr>
            <tr>
                <td class="bold">Meter Reading End Date:</td>
                <td>@mred</td>
            </tr>
            <tr>
                <td class="bold">Billing Days:</td>
                <td>@ViewBag.Invoice["billing-days"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Counter Reading Start:</td>
                <td>@ViewBag.Invoice["counter-reading-start"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Counter Reading End:</td>
                <td>@ViewBag.Invoice["counter-reading-end"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Consumption:</td>
                <td>@ViewBag.Invoice["consumption"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Total Therms:</td>
                <td>@ViewBag.Invoice["total-therms"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Transportation Charges:</td>
                <td>@ViewBag.Invoice["transportation-charges"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">First 50 Therms:</td>
                <td>@ViewBag.Invoice["first-50-therms"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Over 50 Therms:</td>
                <td>@ViewBag.Invoice["over-50-therms"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Delivery Total:</td>
                <td>@ViewBag.Invoice["delivery-total"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Distribution Adjustment:</td>
                <td>@ViewBag.Invoice["distribution-adjustment"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Environmental Charges:</td>
                <td>@ViewBag.Invoice["environmental-charges"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Total Charges:</td>
                <td>@ViewBag.Invoice["total-charges"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Local Taxes:</td>
                <td>@ViewBag.Invoice["local-taxes"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">State Taxes:</td>
                <td>@ViewBag.Invoice["state-taxes"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Payment Due Date:</td>
                <td>@pdd</td>
            </tr>
            <tr>
                <td class="bold">Amount Due:</td>
                <td>@ViewBag.Invoice["amount-due"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Late Amount Due:</td>
                <td>@ViewBag.Invoice["late-amount-due"].ToString()</td>
            </tr>
        </table>
    </div>
    <hr color="black" />
    <p class="text-center">
        @Html.ActionLink("Edit/Update Customer Gas Bill", "Edit",
                         new { id = @ViewBag.Invoice["gas-bill-id"] }, null) ::
        @Html.ActionLink("Cancel this Gas Bill", "Delete",
                         new { id = @ViewBag.Invoice["gas-bill-id"] }, null) ::
        @Html.ActionLink("Customers Gas Bills", "Index")
    </p>
  24. In the Solution Explorer, under Controllers, right-click PaymentsController.cs and click Open
  25. Change the Details() method as follows:
    using System;
    using System.Data;
    using System.IO;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany10.Controllers
    {
        public class PaymentsController : Controller
        {
            
            No Change
    
            // GET: Payments/Details/5
            public ActionResult Details(int id)
            {
                DataRow drInvoice = null;
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
    
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                drInvoice = drPayment;
                            }
                        }
                    }
                }
    
                ViewBag.Payment = drInvoice;
                return View();
            }
    
            . . . No Change
        }
    }
  26. Right-click the code that was written and click Add View...
  27. Make sure the View Name text box displays Details.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  28. Create the webpage as follows:
    @{
        ViewBag.Title = "Payment Details";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string pmtDate = DateTime.Parse(ViewBag.Payment["payment-date"].ToString()).ToLongDateString();
    }
    
    <h2 class="text-center common-font bold">Payment Details</h2>
    
    <hr />
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="medium bold">Payment ID:</td>
                <td>@ViewBag.Payment["payment-id"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Payment Date:</td>
                <td>@pmtDate</td>
            </tr>
            <tr>
                <td class="bold">Gas Bill ID:</td>
                <td>@ViewBag.Payment["gas-bill-id"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Payment Amount:</td>
                <td>@ViewBag.Payment["payment-amount"].ToString()</td>
            </tr>
            <tr>
                <td class="bold">Payment Status:</td>
                <td>@ViewBag.Payment["payment-status"].ToString()</td>
            </tr>
        </table>
    </div>
    <hr color="black" />
    <p class="text-center">
        @Html.ActionLink("Edit/Update Payment Details", "Edit",
                         new { id = @ViewBag.Payment["payment-id"] }, null) ::
        @Html.ActionLink("Cancel tyhis Payment", "Delete",
                         new { id = @ViewBag.Payment["payment-id"] }, null) ::
        @Html.ActionLink("Gas Bills Payments", "Index")
    </p>

The Status of a Record

When a change has been made to a record, a flag should indicate the type of change it has just received. This is referred to as the row state of a record. To support the flags, the System.Data namespace provides an enumeration named DataRowState. To apply this flag to a record, the DataRow class is equipped with a property named RowState.

Making Copies

Imagine you have a table in a data set and the table has the type of structure you want, including the values. You can copy the content of that table and replicate it into a table of your data set. To support this operation, the DataTable class is equipped with a method named Copy. Its syntax is:

public DataTable Copy();

In the same way, you can copy various tables from a data set and replicate them in your data set. If you want to copy all tables from an existing data set into your data set, you can call the Copy() method from the DataSet class. Its syntax is:

public DataSet Copy();

Here is an example:

@{
    System.Xml.DataSet dsSchool = dsStudents.Copy();
}

Editing a Record

Consider the following list of records:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry: Periodic Table</title>
</head>
<body>
<h1>Chemistry</h1>
<h2>Periodic Table</h2>

@{
    System.Data.DataTable dtElements = new System.Data.DataTable("element");

    dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
    dtElements.Columns.Add("symbol", Type.GetType("System.String"));
    dtElements.Columns.Add("element-name", Type.GetType("System.String"));
    dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

    System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
    dsChemistry.Tables.Add(dtElements);

    System.Data.DataRow drElement = dtElements.NewRow();

    drElement[0] = 3;
    drElement[1] = "Li";
    drElement[2] = "Lithium";
    drElement[3] = 6.938f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 1;
    drElement[1] = "H";
    drElement[2] = "Hydrogen";
    drElement[3] = 1.008f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 4;
    drElement[1] = "Be";
    drElement[2] = "Beryllium";
    drElement[3] = 9.0121831f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();

    drElement[0] = 5;
    drElement[1] = "B";
    drElement[2] = "Boron";
    drElement[3] = 10.806f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();

    drElement[0] = 6;
    drElement[1] = "Cb";
    drElement[2] = "Corbone";
    drElement[3] = 12.0096f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();  drElement[0] = 2;

    drElement[1] = "He";
    drElement[2] = "Helium";
    drElement[3] = 4.002602f;
    dtElements.Rows.InsertAt(drElement, 1);
}

@{
    int i = 0;

    <table border="5">
        <tr>
            <td><b>Atomic #</b></td>
            <td><b>Symbol</b></td>
            <td><b>Element Name</b></td>
            <td><b>Atomic Weight</b></td>
        </tr>
    @while (i < dtElements.Rows.Count)
    {
        drElement = dtElements.Rows[i];
        
        <tr>
            <td>@drElement[0]</td>
            <td>@drElement[1]</td>
            <td>@drElement[2]</td>
            <td>@drElement[3]</td>
        </tr>

        i++;
    }
    </table>
}
</body>
</html>

This would produce:

Focus

As mentioned previously, editing a record consists of locating the record, identifying the value that needs to be changed and then changing it. You can perform this operation on one record at a time or on many records. If there are many records to be edited and you don't want a record to be used for anything else while that record is being updated, you can suspend the activities on that record while the updating operation is going on. Before a record is changed, its status is set to DataRowState.Unchanged value.

To let you signal that you are about to edit a record, the DataRow class is equipped with a method named BeginEdit. Its syntax is:

public void BeginEdit();

When this method is called, everything on the record is put on hold. After calling this method, you can perform the desired changes.

After performing the changes, to resume, you should call the EndEdit() method of the DataRow class. Its syntax is:

public void EndEdit();

Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry: Periodic Table</title>
</head>
<body>
<h1>Chemistry</h1>
<h2>Periodic Table</h2>

@{
    System.Data.DataTable dtElements = new System.Data.DataTable("element");

    dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
    dtElements.Columns.Add("symbol", Type.GetType("System.String"));
    dtElements.Columns.Add("element-name", Type.GetType("System.String"));
    dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

    System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
    dsChemistry.Tables.Add(dtElements);

    System.Data.DataRow drElement = dtElements.NewRow();

    drElement[0] = 3;
    drElement[1] = "Li";
    drElement[2] = "Lithium";
    drElement[3] = 6.938f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 1;
    drElement[1] = "H";
    drElement[2] = "Hydrogen";
    drElement[3] = 1.008f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 4;
    drElement[1] = "Be";
    drElement[2] = "Beryllium";
    drElement[3] = 9.0121831f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();

    drElement[0] = 5;
    drElement[1] = "B";
    drElement[2] = "Boron";
    drElement[3] = 10.806f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();

    drElement[0] = 6;
    drElement[1] = "Cb";
    drElement[2] = "Corbone";
    drElement[3] = 12.0096f;
    dtElements.Rows.InsertAt(drElement, 500);

    drElement = dtElements.NewRow();  drElement[0] = 2;

    drElement[1] = "He";
    drElement[2] = "Helium";
    drElement[3] = 4.002602f;
    dtElements.Rows.InsertAt(drElement, 1);
}

@{
    // Edit the 6th record, whose index is 5
    // Let the compiler know that you are starting to edit the record
    dtElements.Rows[5].BeginEdit();
    dtElements.Rows[5][1] = "C";
    dtElements.Rows[5][2] = "Carbon";
    dtElements.Rows[5].EndEdit();

    int i = 0;

    <table border="5">
        <tr>
            <td><b>Atomic #</b></td>
            <td><b>Symbol</b></td>
            <td><b>Element Name</b></td>
            <td><b>Atomic Weight</b></td>
        </tr>
    @while (i < dtElements.Rows.Count)
    {
        drElement = dtElements.Rows[i];
        
        <tr>
            <td>@drElement[0]</td>
            <td>@drElement[1]</td>
            <td>@drElement[2]</td>
            <td>@drElement[3]</td>
        </tr>

        i++;
    }
    </table>
}
</body>
</html>

This would produce:

Students

Notice that the second record has values different than the original. While the changes are going on, if you find out that there is a problem and the record should not be updated, you can cancel the change. To support this, the DataRow class is equipped with a method named CancelEdit. Its syntax is:

public void CancelEdit();

When this method is called, the compiler would dismiss the current change that is being performed on the record.

When a record has been changed, the compiler changes its flag. In this case, it would be flagged as DataRowState.Modified. If you want to manually set this flag, you can call the SetModified() method of the DataRow class. Its syntax is:

public void SetModified();

This method should be called only if the record was previously set to DataRowState.Added or DataRowState.Unchanged.

Practical LearningPractical Learning: Editing a Record

  1. In the Solution Explorer, under Controllers, double-click GasMetersController.cs to access the class
  2. Change both Edit() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasMetersController : Controller
        {
            . . . No Change
    
            // GET: GasMeters/Edit/5
            public ActionResult Edit(int id)
            {
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasMeters.ReadXml(fsGasMeters);
    
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                ViewBag.GasMeter = drGasMeter;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: GasMeters/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    if (System.IO.File.Exists(strGasMetersFile))
                    {
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsGasMeters.ReadXml(fsGasMeters);
                        }
                    }
    
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                drGasMeter.BeginEdit();
                             
                                drGasMeter["meter-number"]       = collection["MeterNumber"];
                                drGasMeter["make"]               = collection["Make"];
                                drGasMeter["model"]              = collection["Model"];
                                drGasMeter["meter-reading-date"] = collection["MeterReadingDate"];
                                drGasMeter["counter-value"]      = collection["CounterValue"];
                             
                                drGasMeter.EndEdit();
    
                                dsGasMeters.WriteXml(fsGasMeters);
    
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  3. Right-click any of the code that was written and click Add View...
  4. In the Add View dialog box, make sure the View Name text box is displaying Edit.
    Make sure the Use A Layout Page text box displays ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  5. Change the webpage as follows:
    @{
        ViewBag.Title = "Edit/Update Gas Meter";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string make = ViewBag.GasMeter["make"].ToString();
        string model = ViewBag.GasMeter["model"].ToString();
        string mtrNumber = ViewBag.GasMeter["meter-number"].ToString();
        string mtrReadDate = DateTime.Parse(ViewBag.GasMeter["meter-reading-date"].ToString()).ToShortDateString();
        string counterValue = ViewBag.GasMeter["counter-value"].ToString();
    }
    
    <h2 class="text-center common-font bold">Edit/Update Gas Meter</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div class="utility-container">
            <table class="common-font">
                <tr>
                    <td class="medium bold">Meter #:</td>
                    <td>@Html.TextBox("MeterNumber", @mtrNumber)</td>
                </tr>
                <tr>
                    <td class="bold">Make:</td>
                    <td>@Html.TextBox("Make", @make)</td>
                </tr>
                <tr>
                    <td class="bold">Model:</td>
                    <td>@Html.TextBox("Model", @model)</td>
                </tr>
                <tr>
                    <td class="large bold">Meter Reading Date:</td>
                    <td> @Html.TextBox("MeterReadingDate", @mtrReadDate)</td>
                </tr>
                <tr>
                    <td class="bold">Counter Value:</td>
                    <td>@Html.TextBox("CounterValue", @counterValue)</td>
                </tr>
            </table>
            <hr />
            <p class="text-center">
                @Html.ActionLink("Gas Meters", "Index") ::<a class="btn btn-warning" href="/GasMeters/Index">Gas Meters</a> 
                <input type="submit" name="btnUpdateGasMeter"
                       value="Update Gas Meter Information" class="btn btn-primary" />
            </p>
        </div>
    }
  6. In the Solution Explorer, under Controllers, double-click CustomersController.cs to access the controller
  7. Change both Edit() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class CustomersController : Controller
        {
            . . . No Change
    
            // GET: Customers/Edit/5
            public ActionResult Edit(int id)
            {
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsCustomers);
    
                        foreach (DataRow drCustomer in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drCustomer["customer-id"].ToString()) == id)
                            {
                                ViewBag.Customer = drCustomer;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Customers/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                    if (System.IO.File.Exists(strCustomersFile))
                    {
                        using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsCustomers.ReadXml(fsCustomers);
                        }
                    }
    
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drCustomer in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drCustomer["customer-id"].ToString()) == id)
                            {
                                drCustomer.BeginEdit();
                                drCustomer["account-number"] = collection["AccountNumber"];
                                drCustomer["meter-number"]   = collection["MeterNumber"];
                                drCustomer["first-name"]     = collection["FirstName"];
                                drCustomer["last-name"]      = collection["LastName"];
                                drCustomer["address"]        = collection["Address"];
                                drCustomer["city"]           = collection["City"];
                                drCustomer["county"]         = collection["County"];
                                drCustomer["state"]          = collection["State"];
                                drCustomer["zip-code"]       = collection["ZIPCode"];
                                drCustomer.EndEdit();
    
                                dsCustomers.WriteXml(fsCustomers);
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  8. In the document, right-click any of the Edit() methods and click Add View...
  9. In the Add View dialog box, make sure the View Name text box displays Edit.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  10. Change the code as follows:
    @{
        ViewBag.Title = "Edit/Update Customer Account";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string acntNbr = ViewBag.Customer["account-number"].ToString();
        string mtrNbr  = ViewBag.Customer["meter-number"].ToString();
        string fname   = ViewBag.Customer["first-name"].ToString();
        string lname   = ViewBag.Customer["last-name"].ToString();
        string adrs    = ViewBag.Customer["address"].ToString();
        string city    = ViewBag.Customer["city"].ToString();
        string county  = ViewBag.Customer["county"].ToString();
        string state   = ViewBag.Customer["state"].ToString();
        string zip     = ViewBag.Customer["zip-code"].ToString();
    }
    
    <h2 class="text-center common-font bold">Edit/Update Customer Account</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div class="utility-container">
            <table class="common-font">
                <tr>
                    <td class="medium bold">Account #:</td>
                    <td>@Html.TextBox("AccountNumber", @acntNbr)</td>
                </tr>
                <tr>
                    <td class="bold">Meter #:</td>
                    <td>@Html.TextBox("MeterNumber", @mtrNbr)</td>
                </tr>
                <tr>
                    <td class="bold">First Name:</td>
                    <td>@Html.TextBox("FirstName", @fname)</td>
                </tr>
                <tr>
                    <td class="bold">Last Name:</td>
                    <td>@Html.TextBox("LastName", @lname)</td>
                </tr>
                <tr>
                    <td class="bold">Address:</td>
                    <td>@Html.TextBox("Address", @adrs)</td>
                </tr>
                <tr>
                    <td class="bold">City:</td>
                    <td>@Html.TextBox("City", @city)</td>
                </tr>
                <tr>
                    <td class="bold">County:</td>
                    <td>@Html.TextBox("County", @county)</td>
                </tr>
                <tr>
                    <td class="bold">State:</td>
                    <td>@Html.TextBox("State", @state)</td>
                </tr>
                <tr>
                    <td class="bold">ZIP-Code:</td>
                    <td>@Html.TextBox("ZIPCode", @zip)</td>
                </tr>
            </table>
            <hr />
            <p class="text-center">
                <a class="btn btn-warning" href="/Customers/Index">Customers Accounts</a> 
                <input type="submit" name="btnUpdateCustomerAccount"
                       value="Update Customer Account" class="btn btn-primary" />
            </p>
        </div>
    }
  11. In the Solution Explorer, under Controllers, double-click GasBillsController.cs
  12. Implement the second Create() and the Edit() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasBillsController : Controller
        {
    
            . . . No Change
    
            // GET: GasBills/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: GasBills/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    string meterNumber = string.Empty;
                    string accountNumber = string.Empty;
                    string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        if (System.IO.File.Exists(strGasBillsFile))
                        {
                            using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                dsGasBills.ReadXml(fsGasBills);
                            }
                        }
    
                        DataRow drGasBill = dtGasBills.NewRow();
    
                        accountNumber = collection["AccountNumber"];
    
                        drGasBill["account-number"] = collection["AccountNumber"];
                        drGasBill["meter-reading-start-date"] = collection["MeterReadingStartDate"];
                        drGasBill["meter-reading-end-date"] = collection["MeterReadingEndDate"];
                        drGasBill["billing-days"] = collection["BillingDays"];
                        drGasBill["counter-reading-start"] = collection["CounterReadingStart"];
                        drGasBill["counter-reading-end"] = collection["CounterReadingEnd"];
                        drGasBill["consumption"] = collection["Consumption"];
                        drGasBill["total-therms"] = collection["TotalTherms"];
                        drGasBill["transportation-charges"] = collection["TransportationCharges"];
                        drGasBill["first-50-therms"] = collection["First50Therms"];
                        drGasBill["over-50-therms"] = collection["Over50Therms"];
                        drGasBill["delivery-total"] = collection["DeliveryTotal"];
                        drGasBill["distribution-adjustment"] = collection["DistributionAdjustment"];
                        drGasBill["environmental-charges"] = collection["EnvironmentalCharges"];
                        drGasBill["total-charges"] = collection["TotalCharges"];
                        drGasBill["local-taxes"] = collection["LocalTaxes"];
                        drGasBill["state-taxes"] = collection["StateTaxes"];
                        drGasBill["payment-due-date"] = collection["PaymentDueDate"];
                        drGasBill["amount-due"] = collection["AmountDue"];
                        drGasBill["late-amount-due"] = collection["LateAmountDue"];
                        
                        dtGasBills.Rows.Add(drGasBill);
    
                        using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                        {
                            dsGasBills.WriteXml(fsGasBills);
                        }
    
                        CustomersController clientController = new CustomersController();
    
                        if (System.IO.File.Exists(strCustomersFile))
                        {
                            using (FileStream fsGasMeters = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                clientController.dsCustomers.ReadXml(fsGasMeters);
    
                                foreach (DataRow drClient in clientController.dsCustomers.Tables[0].Rows)
                                {
                                    if (drClient["account-number"].ToString() == accountNumber)
                                    {
                                        meterNumber = drClient["meter-number"].ToString();
                                    }
                                }
                            }
                        }
    
                        GasMetersController gmc = new GasMetersController();
    
                        if (System.IO.File.Exists(strGasMetersFile))
                        {
                            using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                gmc.dsGasMeters.ReadXml(fsGasMeters);
                            }
                        }
    
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (DataRow drGasMeter in gmc.dsGasMeters.Tables[0].Rows)
                            {
                                if (drGasMeter["meter-number"].ToString() == meterNumber)
                                {
                                    drGasMeter.BeginEdit();
                                    drGasMeter["meter-reading-date"] = collection["MeterReadingEndDate"];
                                    drGasMeter["counter-value"] = collection["CounterReadingEnd"];
                                    drGasMeter.EndEdit();
    
                                    gmc.dsGasMeters.WriteXml(fsGasMeters);
    
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: GasBills/Edit/5
            public ActionResult Edit(int id)
            {
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
    
                        foreach (DataRow drGasBill in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drGasBill["gas-bill-id"].ToString()) == id)
                            {
                                ViewBag.GasBill = drGasBill;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: GasBills/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                    if (System.IO.File.Exists(strGasBillsFile))
                    {
                        using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsGasBills.ReadXml(fsGasBills);
                        }
                    }
    
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drGasBill in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drGasBill["gas-bill-id"].ToString()) == id)
                            {
                                drGasBill.BeginEdit();
                                drGasBill["account-number"] = collection["AccountNumber"];
                                drGasBill["meter-reading-start-date"] = collection["MeterReadingStartDate"];
                                drGasBill["meter-reading-end-date"] = collection["MeterReadingEndDate"];
                                drGasBill["billing-days"] = collection["BillingDays"];
                                drGasBill["counter-reading-start"] = collection["CounterReadingStart"];
                                drGasBill["counter-reading-end"] = collection["CounterReadingEnd"];
                                drGasBill["consumption"] = collection["Consumption"];
                                drGasBill["total-therms"] = collection["TotalTherms"];
                                drGasBill["transportation-charges"] = collection["TransportationCharges"];
                                drGasBill["first-50-therms"] = collection["First50Therms"];
                                drGasBill["over-50-therms"] = collection["Over50Therms"];
                                drGasBill["delivery-total"] = collection["DeliveryTotal"];
                                drGasBill["distribution-adjustment"] = collection["DistributionAdjustment"];
                                drGasBill["environmental-charges"] = collection["EnvironmentalCharges"];
                                drGasBill["total-charges"] = collection["TotalCharges"];
                                drGasBill["local-taxes"] = collection["LocalTaxes"];
                                drGasBill["state-taxes"] = collection["StateTaxes"];
                                drGasBill["payment-due-date"] = collection["PaymentDueDate"];
                                drGasBill["amount-due"] = collection["AmountDue"];
                                drGasBill["late-amount-due"] = collection["LateAmountDue"];
                                drGasBill.EndEdit();
    
                                dsGasBills.WriteXml(fsGasBills);
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  13. In the class, right-click one of the Create() methods and click Add View...
  14. Make sure the View Name text box displays Create.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  15. Create a form as follows:
    @{
        ViewBag.Title = "Gas Bill Creation";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Prepare Gas Bill</h2>
    
    @using (Html.BeginForm())
    {
    <div>
        <table class="common-font">
            <tr>
                <td class="large bold">Customer Account #:</td>
                <td>@Html.TextBox("AccountNumber", null,
                                   htmlAttributes: new { id = "accountNumber" })</td>
            </tr>
            <tr>
                <td class="bold">Customer Name:</td>
                <td><span id="customerName" class="sub-title"></span></td>
            </tr>
            <tr>
                <td class="bold">Address:</td>
                <td><span id="address" class="sub-title"></span></td>
            </tr>
            <tr>
                <td class="bold">Gas Meter:</td>
                <td><span id="gasMeterNbr" class="sub-title"></span>
                    <span id="gasMeterDetails" class="sub-title"></span></td>
            </tr>
        </table>
        <table class="common-font">
            <tr>
                <td class="large bold">Meter Reading Start Date:</td>
                <td>@Html.TextBox("MeterReadingStartDate", null,
                                  htmlAttributes: new { id = "mrsd" })</td>
                <td class="bold">Reading End Date:</td>
                <td>@Html.TextBox("MeterReadingEndDate", null,
                                  htmlAttributes: new { type = "date", id = "mred" })</td>
                <td class="bold">Billing Days:</td>
                <td>@Html.TextBox("BillingDays", null,
                                  htmlAttributes: new { @class = "small", id = "days" })</td>
            </tr>
            <tr>
                <td class="bold">Counter Reading Start:</td>
                <td>@Html.TextBox("CounterReadingStart", null,
                                 htmlAttributes: new { id = "crs" })</td>
                <td class="bold">Current Meter Reading:</td>
                <td>@Html.TextBox("CounterReadingEnd", null,
                                  htmlAttributes: new { id = "cre" })</td>
                <td class="bold">Consumption:</td>
                <td>@Html.TextBox("Consumption", null,
                                  htmlAttributes: new { @class = "small", id = "consumption" })</td>
            </tr>
        </table>
        <hr />
        <table class="common-font">
            <tr>
                <td class="large bold">Total Therms:</td>
                <td>@Html.TextBox("TotalTherms", null,
                                  htmlAttributes: new { id = "totalTherms" })</td>
                <td class="bold">First 50 Therms:</td>
                <td>@Html.TextBox("First50Therms", null,
                                  htmlAttributes: new { id = "first50Therms" })</td>
                <td class="bold">Over 50 Therms:</td>
                <td>@Html.TextBox("Over50Therms", null,
                                  htmlAttributes: new { @class = "small", id = "over50Therms" })</td>
            </tr>
            <tr>
                <td class="bold">Delivery Total:</td>
                <td>@Html.TextBox("DeliveryTotal", null,
                                  htmlAttributes: new { id = "deliveryTotal" })</td>
                <td class="bold">Distribution Adjustment:</td>
                <td>@Html.TextBox("DistributionAdjustment", null,
                                  htmlAttributes: new { id = "distributionAdjustment" })</td>
                <td class="bold">Environmental Charges:</td>
                <td>@Html.TextBox("EnvironmentalCharges", null,
                                  htmlAttributes: new { @class = "small", id = "environmentalCharges" })</td>
            </tr>
            <tr>
                <td colspan="6"><hr /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="bold">Transportation Charges:</td>
                <td>@Html.TextBox("transportationCharges", null,
                                  htmlAttributes: new { id = "transportation" })</td>
                <td class="bold">Total Charges:</td>
                <td>@Html.TextBox("TotalCharges", null,
                                  htmlAttributes: new { @class = "small", id = "totalCharges" })</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="bold">Local Taxes:</td>
                <td>@Html.TextBox("LocalTaxes", null,
                              htmlAttributes: new { id = "localTaxes" })</td>
                <td class="bold">State Taxes:</td>
                <td>@Html.TextBox("StateTaxes", null,
                                  htmlAttributes: new { @class = "small", id = "stateTaxes" })</td>
            </tr>
            <tr>
                <td class="bold">Payment Due Date:</td>
                <td>@Html.TextBox("PaymentDueDate", null,
                                  htmlAttributes: new { type = "date" })</td>
                <td class="bold">Amount Due:</td>
                <td>@Html.TextBox("AmountDue", null,
                                  htmlAttributes: new { id = "amtDue" })</td>
                <td class="bold">Late Amount Due:</td>
                <td>@Html.TextBox("LateAmountDue", null,
                                  htmlAttributes: new { @class = "small", id = "lad" })</td>
            </tr>
        </table>
        <hr />
        <p class="text-center"><input type="submit" name="btnCreateGasBill"
               value="Generate Customer Gas Bill" class="btn btn-warning" /></p>
    </div>
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            var mtrNbr = "";
            $("#transportation").val(10.55);
    
            /* After the user has entered a customer account number and 
             * press Tab (or clicks somewhere else), ... */
            $("#accountNumber").blur(function (event) {
                /* ... we will check the customer account ... */
                $.ajax({
                    method:   "GET",
                    dataType: "xml",
                    url:      "/GasDistribution/Customers.xml",
                    success: function (data) {
                        var customers = $(data).find("customer");
                        customers.each(function () {
                            if ($(this).find("account-number").text() === $("#accountNumber").val()) {
                                /* and get the necessary values of the record to display in the form. */
                                $("#customerName").text($(this).find("first-name").text() + " " + $(this).find("last-name").text());
                                $("#address").text($(this).find("address").text() + " " + $(this).find("city").text() + ", " + $(this).find("state").text());
                                $("#gasMeterNbr").text($(this).find("meter-number").text());
                                // We will also get the meter number allocated to the customer
                                mtrNbr = $(this).find("meter-number").text();
                            }
                        }); // Each Customer
                    } // Success
                }); // Ajax Customers
    
                // Based on the meter number of the customer, we can locate the gas meter, ...
                $.ajax({
                    method:   "GET",
                    dataType: "xml",
                    url:      "/GasDistribution/GasMeters.xml",
                    success: function (data) {
                        var gasMeters = $(data).find("gas-meter");
                        gasMeters.each(function () {
                            if ($(this).find("meter-number").text() === mtrNbr) {
                                // ... and display its details
                                $("#gasMeterDetails").text($(this).find("make").text() + " " + $(this).find("model").text());
                                /* In case this is the first gas bill for the customer, get the previous 
                                 * counter reading number from the gas meter record */
                                $("#crs").val($(this).find("counter-value").text());
                                // In the same way, get the previous meter reading date from the gas meter record
                                $("#mrsd").val($(this).find("meter-reading-date").text());
                            }
                        }); // Each Gas Meter
                    } // Success
                }); // Ajax
    
                /* If this is not the customer's first bill, this means that the previous 
                 * counter reading and date are stored in the file for gas bills. */
                $.ajax({
                    method:   "GET",
                    dataType: "xml",
                    url:      "/GasDistribution/GasBills.xml",
                    success: function (data) {
                        // Get the gas bills from the file
                        var gasBills = $(data).find("gas-bill");
                        // Check each gas bill
                        gasBills.each(function () {
                            // If you find a record that has the same account number as the one the user had typed, ...
                            if ($(this).find("account-number").text() === $("#accountNumber").val()) {
                                // get the record's Meter Reading Start Date value as the previous meter reading date
                                $("#mrsd").val($(this).find("meter-reading-end-date").text());
                                /* and its Counter Reading End value as the Counter Reading Start value, ... */
                                $("#crs").val($(this).find("counter-reading-end").text());
                            }
                        }); // Each Gas Bill
                    } // Success
                }); // Ajax
            }); // Lost Focus Event
    
            $("#mred").on("blur", function (event) {
                var startDate = new Date($("#mrsd").val()).getTime();
                var endDate = new Date($("#mred").val()).getTime();
    
                var days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
    
                $("#days").val(days);
            });
    
            $("#cre").on("blur", function (event) {
                var first50Therms = 0, over50Therms = 0;
    
                var readingStart = parseInt($("#crs").val());
                var readingEnd   = parseInt($("#cre").val());
    
                var difference = readingEnd - readingStart;
                var totalTherms = difference * 1.0367;
    
                if (totalTherms < 50) {
                    first50Therms = totalTherms * 0.5269;
                    over50Therms = 0;
                } else {
                    first50Therms = 50 * 0.5269;
                    over50Therms = (totalTherms - 50) * 0.4995;
                }
    
                var transportation = parseInt($("#transportation").val());
                var deliveryTotal = transportation + first50Therms + over50Therms;
                var distribution = totalTherms * 0.11086;
                var environment = deliveryTotal * 0.0045;
                var totalCharges = transportation + deliveryTotal + distribution + environment;
                var local = totalCharges * 0.05826;
                var state = totalCharges * 0.0225;
                var amtDue = totalCharges + local + state;
    
                $("#consumption").val(difference.toFixed());
                $("#totalTherms").val(totalTherms.toFixed(2));
                $("#first50Therms").val(first50Therms.toFixed(2));
                $("#over50Therms").val(over50Therms.toFixed(2));
                $("#deliveryTotal").val(deliveryTotal.toFixed(2));
                $("#distributionAdjustment").val(distribution.toFixed(2));
                $("#environmentalCharges").val(environment.toFixed(2));
                $("#totalCharges").val(totalCharges.toFixed(2));
                $("#localTaxes").val(local.toFixed(2));
                $("#stateTaxes").val(state.toFixed(2));
                $("#amtDue").val(amtDue.toFixed(2));
                $("#lad").val((amtDue + 8.75).toFixed(2));
            });
        }); // Document.Ready
    </script>
  16. In the class, right-click one of the Edit() methods and click Add View...
  17. Make sure the View Name text box displays Edit.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  18. Create a form as follows:
    @{
        ViewBag.Title = "Edit/Update Gas Bill";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string mrsd           = DateTime.Parse(ViewBag.GasBill["meter-reading-start-date"].ToString()).ToShortDateString();
        string mred           = DateTime.Parse(ViewBag.GasBill["meter-reading-end-date"].ToString()).ToShortDateString();
        string days           = ViewBag.GasBill["billing-days"].ToString();
        string crs            = ViewBag.GasBill["counter-reading-start"].ToString();
        string cre            = ViewBag.GasBill["counter-reading-end"].ToString();
        string totalTherms    = ViewBag.GasBill["total-therms"].ToString();
        string consumption    = ViewBag.GasBill["consumption"].ToString();
        string transportation = ViewBag.GasBill["transportation-charges"].ToString();
        string first50Therms  = ViewBag.GasBill["first-50-therms"].ToString();
        string over50Therms   = ViewBag.GasBill["over-50-therms"].ToString();
        string delivery       = ViewBag.GasBill["delivery-total"].ToString();
        string distribution   = ViewBag.GasBill["distribution-adjustment"].ToString();
        string environment    = ViewBag.GasBill["environmental-charges"].ToString();
        string totalCharges   = ViewBag.GasBill["total-charges"].ToString();
        string localTaxes     = ViewBag.GasBill["local-taxes"].ToString();
        string stateTaxes     = ViewBag.GasBill["state-taxes"].ToString();
        string pdd            = DateTime.Parse(ViewBag.GasBill["payment-due-date"].ToString()).ToShortDateString();
        string amtDue         = ViewBag.GasBill["amount-due"].ToString();
        string lad            = ViewBag.GasBill["late-amount-due"].ToString();
    }
    
    <h2 class="text-center common-font bold">Edit/Update Gas Bill</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div>
            <table class="common-font">
                <tr>
                    <td class="large bold">Customer Account #:</td>
                    <td>@Html.TextBox("AccountNumber", @ViewBag.GasBill["account-number"] as string,
                                      htmlAttributes: new { id = "accountNumber" })</td>
                </tr>
                <tr>
                    <td class="bold">Customer Name:</td>
                    <td><span id="customerName" class="sub-title"></span></td>
                </tr>
                <tr>
                    <td class="bold">Address:</td>
                    <td><span id="address" class="sub-title"></span></td>
                </tr>
                <tr>
                    <td class="bold">Gas Meter:</td>
                    <td>
                        <span id="gasMeterNbr" class="sub-title"></span>
                        <span id="gasMeterDetails" class="sub-title"></span>
                    </td>
                </tr>
            </table>
            <table class="common-font">
                <tr>
                    <td class="large bold">Meter Reading Start Date:</td>
                    <td>@Html.TextBox("MeterReadingStartDate", @mrsd,
                                      htmlAttributes: new { id = "mrsd" })</td>
                    <td class="bold">Reading End Date:</td>
                    <td>@Html.TextBox("MeterReadingEndDate", @mred,
                                      htmlAttributes: new { id = "mred" })</td>
                    <td class="bold">Billing Days:</td>
                    <td>@Html.TextBox("BillingDays", @days,
                                      htmlAttributes: new { @class = "small", id = "days" })</td>
                </tr>
                <tr>
                    <td class="bold">Counter Reading Start:</td>
                    <td>@Html.TextBox("CounterReadingStart", @crs,
                                      htmlAttributes: new { id = "crs" })</td>
                    <td class="bold">Current Meter Reading:</td>
                    <td>@Html.TextBox("CounterReadingEnd", @cre,
                                      htmlAttributes: new { id = "cre" })</td>
                    <td class="bold">Consumption:</td>
                    <td>@Html.TextBox("Consumption", @consumption,
                                      htmlAttributes: new { @class = "small", id = "consumption" })</td>
                </tr>
            </table>
            <hr />
            <table class="common-font">
                <tr>
                    <td class="large bold">Total Therms:</td>
                    <td>@Html.TextBox("TotalTherms", @totalTherms,
                                      htmlAttributes: new { id = "totalTherms" })</td>
                    <td class="bold">First 50 Therms:</td>
                    <td>@Html.TextBox("First50Therms", @first50Therms,
                                      htmlAttributes: new { id = "first50Therms" })</td>
                    <td class="bold">Over 50 Therms:</td>
                    <td>@Html.TextBox("Over50Therms", @over50Therms,
                                      htmlAttributes: new { @class = "small", id = "over50Therms" })</td>
                </tr>
                <tr>
                    <td class="bold">Delivery Total:</td>
                    <td>@Html.TextBox("DeliveryTotal", @delivery,
                                      htmlAttributes: new { id = "deliveryTotal" })</td>
                    <td class="bold">Distribution Adjustment:</td>
                    <td>@Html.TextBox("DistributionAdjustment", @distribution,
                                      htmlAttributes: new { id = "distribution" })</td>
                    <td class="bold">Environmental Charges:</td>
                    <td>@Html.TextBox("EnvironmentalCharges", @environment,
                                      htmlAttributes: new { @class = "small", id = "environment" })</td>
                </tr>
                <tr>
                    <td colspan="6"><hr /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td class="bold">Transportation Charges:</td>
                    <td>@Html.TextBox("transportationCharges", @transportation,
                                      htmlAttributes: new { id = "transportation" })</td>
                    <td class="bold">Total Charges:</td>
                    <td>@Html.TextBox("TotalCharges", @totalCharges,
                                      htmlAttributes: new { @class = "small", id = "totalCharges" })</td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td class="bold">Local Taxes:</td>
                    <td>@Html.TextBox("LocalTaxes", @localTaxes,
                                      htmlAttributes: new { id = "localTaxes" })</td>
                    <td class="bold">State Taxes:</td>
                    <td>@Html.TextBox("StateTaxes", @stateTaxes,
                                      htmlAttributes: new { @class = "small", id = "stateTaxes" })</td>
                </tr>
                <tr>
                    <td class="bold">Payment Due Date:</td>
                    <td>@Html.TextBox("PaymentDueDate", @pdd,
                                      htmlAttributes: new { id = "pdd" })</td>
                    <td class="bold">Amount Due:</td>
                    <td>@Html.TextBox("AmountDue", @amtDue,
                                      htmlAttributes: new { id = "amtDue" })</td>
                    <td class="bold">Late Amount Due:</td>
                    <td>@Html.TextBox("LateAmountDue", @lad,
                                      htmlAttributes: new { @class = "small", id = "lad" })</td>
                </tr>
            </table>
            <hr />
            <p class="text-center">
                @Html.ActionLink("Gas Bills", "Index") ::
                <input type="submit" name="btnUpdateGasBill"
                       value="Update Gas Bill" class="btn btn-primary" />
            </p>
        </div>
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            var mtrNbr = "";
    
            function getCustomer() {
                $.ajax({
                    method:   "GET",
                    dataType: "xml",
                    url:      "/GasDistribution/Customers.xml",
                    success: function (data) {
                        var customers = $(data).find("customer");
                        customers.each(function () {
                            if ($(this).find("account-number").text() === $("#accountNumber").val()) {
                                $("#customerName").text($(this).find("first-name").text() + " " + $(this).find("last-name").text());
                                $("#address").text($(this).find("address").text() + " " + $(this).find("city").text() + ", " + $(this).find("state").text());
                                $("#gasMeterNbr").text($(this).find("meter-number").text());
                                mtrNbr = $(this).find("meter-number").text();
                            }
                        }); // Each Customer
                    } // Success
                }); // Ajax Customers
    
                $.ajax({
                    method:   "GET",
                    dataType: "xml",
                    url:      "/GasDistribution/GasMeters.xml",
                    success: function (data) {
                        var gasMeters = $(data).find("gas-meter");
                        gasMeters.each(function () {
                            if ($(this).find("meter-number").text() === mtrNbr) {
                                $("#gasMeterDetails").text($(this).find("make").text() + " " + $(this).find("model").text());  
                            }
                        }); // Each Gas Meter
                    } // Success
                }); // Ajax
            }
    
            getCustomer();
    
            $("#accountNumber").blur(function (event) {
                getCustomer();    
            }); // Lost Focus Event
    
            $("#mred").on("blur", function (event) {
                var startDate = new Date($("#mrsd").val()).getTime();
                var endDate = new Date($("#mred").val()).getTime();
    
                var days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
    
                $("#days").val(days);
            });
            
            $("#cre").on("blur", function (event) {
                var first50Therms = 0, over50Therms = 0;
    
                var readingStart = parseInt($("#crs").val());
                var readingEnd   = parseInt($("#cre").val());
    
                var difference   = readingEnd - readingStart;
                var totalTherms  = difference * 1.0367;
    
                if (totalTherms < 50) {
                    first50Therms = totalTherms * 0.5269;
                    over50Therms = 0;
                } else {
                    first50Therms = 50 * 0.5269;
                    over50Therms  = (totalTherms - 50) * 0.4995;
                }
    
                var transportation = parseInt($("#transportation").val());
                var deliveryTotal  = transportation + first50Therms + over50Therms;
                var distribution   = totalTherms * 0.11086;
                var environment    = deliveryTotal * 0.0045;
                var totalCharges   = transportation + deliveryTotal + distribution + environment;
                var local          = totalCharges * 0.05826;
                var state          = totalCharges * 0.0225;
                var amtDue         = totalCharges + local + state;
    
                $("#consumption").val(difference.toFixed(2));
                $("#totalTherms").val(totalTherms.toFixed(2));
                $("#first50Therms").val(first50Therms.toFixed(2));
                $("#over50Therms").val(over50Therms.toFixed(2));
                $("#deliveryTotal").val(deliveryTotal.toFixed(2));
                $("#distributionAdjustment").val(distribution.toFixed(2));
                $("#environmentalCharges").val(environment.toFixed(2));
                $("#totalCharges").val(totalCharges.toFixed(2));
                $("#localTaxes").val(local.toFixed(2));
                $("#stateTaxes").val(state.toFixed(2));
                $("#amtDue").val(amtDue.toFixed(2));
                $("#lad").val((amtDue + 8.75).toFixed(2));
            });
        }); // Document.Ready
    </script>
  19. In the Solution Explorer, Under Controllers, double-click PaymentsController.cs
  20. Change the Edit() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class PaymentsController : Controller
        {           
    
            . . . No Change
    
            // GET: Payments/Edit/5
            public ActionResult Edit(int id)
            {
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
                        
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                ViewBag.Payment = drPayment;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Payments/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                    if (System.IO.File.Exists(strPaymentsFile))
                    {
                        using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsPayments.ReadXml(fsPayments);
                        }
                    }
                    
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                drPayment.BeginEdit();
    
                                drPayment["payment-date"]   = collection["PaymentDate"];
                                drPayment["gas-bill-id"]    = collection["GasBillID"];
                                drPayment["payment-amount"] = collection["PaymentAmount"];
                                drPayment["payment-status"] = collection["PaymentStatus"];
                                
                                drPayment.EndEdit();
    
                                dsPayments.WriteXml(fsPayments);
                                
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  21. In the class, right-click one of the Edit() methods and click Add View...
  22. Make sure the View Name text box displays Edit.
    Make sure the Use A Layout Page text box is displaying ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  23. Create a form as follows:
    @{
        ViewBag.Title = "Edit/Update Bill Payment";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string billNbr = ViewBag.Payment["gas-bill-id"].ToString();
        string status  = ViewBag.Payment["payment-status"].ToString();
        string amt     = ViewBag.Payment["payment-amount"].ToString();
        string pmtDate = DateTime.Parse(ViewBag.Payment["payment-date"].ToString()).ToShortDateString();
    
        System.Collections.Generic.List<SelectListItem> categories = new List<SelectListItem>();
    
        categories.Add(new SelectListItem { Text = "On Time",      Value = "On Time",      Selected = (status == "On Time") });
        categories.Add(new SelectListItem { Text = "Late Payment", Value = "Late Payment", Selected = (status == "Late Payment") });
    }
    
    <h2 class="text-center common-font bold">Edit/Update Bill Payment</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div class="utility-container">
            <table class="common-font">
                <tr>
                    <td class="medium bold">Payment Date:</td>
                    <td>@Html.TextBox("PaymentDate", @pmtDate)</td>
                </tr>
                <tr>
                    <td class="bold">Gas Bill ID:</td>
                    <td>@Html.TextBox("GasBillID", @billNbr)</td>
                </tr>
                <tr>
                    <td class="bold">Payment Amount:</td>
                    <td>@Html.TextBox("PaymentAmount", @amt)</td>
                </tr>
                <tr>
                    <td class="large bold">Payment Status:</td>
                    <td>@Html.DropDownList("PaymentStatus", @categories, htmlAttributes: new { value = "" })</td>
                </tr>
            </table>
            <hr />
            <p class="text-center">
                <a href="/Payments/Index" class="btn btn-warning">Gas Bills Payments</a> 
                <input type="submit" name="btnUpdateBillPayment"
                       value="Update Gas Bill Payment" class="btn btn-warning" />
            </p>
        </div>
    }
  24. In the Solution Explorer, under Views, expand Home, and double-click Index.cshtml
  25. Change the webpage as follows:
    @{
        ViewBag.Title = "GUC Home";
    }
    
    <div class="jumbotron">
        <h1>Your Gas Needs With Us</h1>
        <p class="lead">The Gas Utility Company (GUC) serves the whole Metropolitan
            area and its vicinity. The company serves both residential and business
            needs in terms of natural gas.</p>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            <h2>Employees</h2>
            <p>Employees should log in to review their
                time sheet and benefits.</p>
            @Html.ActionLink("Employees Portal", "Index", "Employees")
        </div>
        <div class="col-md-4">
            <h2>Customers</h2>
            <p>To review or pay your bills, first log in, or create an account.</p>
            @Html.ActionLink("Customers Topics", "Index", "Customers")
        </div>
        <div class="col-md-4">
    
            <h2>Gas Meters</h2>
            <p>This section provides much information about our gas
                meters.</p>
            @Html.ActionLink("Gas Meters", "Index", "GasMeters")
        </div>
    </div>
  26. Press Ctrl + F5 to execute the application

    Data Sets Maintenance

  27. Click the Gas Meters link

    Introduction to Maintenance of Data Sets

  28. Click the Details link of the second record:

    Maintenance of Data Sets - Finding a Record

  29. Click the Edit/Update Gas Meter Information link
  30. Change the third record as follows:
    Make:          Archimeda
    Counter Value: 2866

    Data Sets Maintenance - New Gas Meters

  31. Click the Update Gas Meter Information button

    Introduction to Maintenance of Data Sets

  32. Click the Customers link
  33. Click the New Customer Account link
  34. Create a few records as follows:

    tr>
    Account # Meter # First Name Last Name Address City County State ZIP-Code
    82-1397-851 425837-14 Christopher Mack Gillan 3316 Sanderson Rd Alexandria   VA  
    82-9360-597 582741-38 Sandra Rhodes 11158 Grattos Ave Hyattsville Prince George MD 20783
    29-5384-805 928731-59 Marco Ramos 9012 Jefferson Crt Washington   DC 20012
    92-3848-393 797047-27 Gabrielle Bayley 799 Boomerang Str Columbia Howard MD  

    Passing an Array By Reference

  35. Click the Details link of the first record:

    Maintenance of Data Sets - Finding a Record

  36. On the webpage, click the Customers Accounts link
  37. Click to Edit link of the second record

    Data Sets Maintenance - New Gas Meters

  38. Change the Last Name to McGee
  39. Set the ZIP Code to 22314

    Data Sets Maintenance - New Gas Meters

  40. Click the Update Customer Account button

    Passing an Array By Reference

  41. Click the Gas Bills link

    Passing an Array By Reference

  42. Click the New Gas Bill link

    Data Sets Maintenance - New Gas Meters

  43. Create a few records as follows:

    Data Sets Maintenance - New Gas Meters

    Data Sets Maintenance - New Gas Meters

    Data Sets Maintenance - New Gas Meters

    Data Sets Maintenance - New Gas Meters

    Data Sets Maintenance - New Gas Meters

    Account # Reading End Date Counter Reading End Payment Due Date
    60-9720-824 2/20/2018 3024 03/17/2018
    82-9360-597 2/22/2018 165 03/19/2018
    92-3848-393 2/25/2018 997 3/22/2018
    29-5384-805 2/28/2018 8418 3/25/2018
    60-9720-824 3/15/2018 3195 4/9/2018
    92-3848-393 3/24/2018 1229 4/18/2018
    82-1397-851 3/22/2018 6156 4/16/2018
    29-5384-805 3/31/2018 8808 4/25/2018
    82-1397-851 4/19/2018 6288 5/24/2018
    60-9720-824 4/20/2018 3407 5/15/2018
    82-1397-851 5/21/2018 6338 06-15-2018

    Passing an Array By Reference

  44. Click the Payments link

    Passing an Array By Reference

  45. Click the New Bill Payment link

    Data Sets Maintenance - New Gas Meters

  46. Create a few records as follows:

    Data Sets Maintenance - New Gas Meters

    Gas Bill # Payment Date Payment Amount Payment Status
    1 3/5/2018 131.60 On Time
    3 3/6/2018 209.85 On Time
    2 3/30/2018 49.78 Late Payment
    6 4/1/2018 182.39 On Time
    4 4/2/2018 307.83 Late Payment
    5 4/5/2018 140.52 On Time
    8 4/15/2018 290.84 On Time
    7 4/30/2018 60.54 Late Payment

    Passing an Array By Reference

  47. Close the browser and return to your programming environment

Accepting Record Changes

The operations you perform on records, such as adding a new record, adding a series of records, deleting a record, deleting a group or records, or deleting all records, are referred to as changes. After preparing a change but before committing it, if you know the change is right, you can ask the compiler to accept it. To support this, the DataRow class is equipped with a method named AcceptChanges. Its syntax is:

public void AcceptChanges()

This method allows you to ask the compiler to validate the changes that are about to be made on a record. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry: Periodic Table</title>
</head>
<body>
<h1>Chemistry</h1>
<h2>Periodic Table</h2>

@{
    System.Data.DataTable dtElements = new System.Data.DataTable("element");

    dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
    dtElements.Columns.Add("symbol", Type.GetType("System.String"));
    dtElements.Columns.Add("element-name", Type.GetType("System.String"));
    dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

    System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
    dsChemistry.Tables.Add(dtElements);

    System.Data.DataRow drElement = dtElements.NewRow();

    drElement[0] = 21;
    drElement[1] = "Sc";
    drElement[2] = "Scandium";
    drElement[3] = 44.955908f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 22;
    drElement[1] = "Ti";
    drElement[2] = "Titanium";
    drElement[3] = 47.867f;
    dtElements.Rows.InsertAt(drElement, 1);

    drElement = dtElements.NewRow();

    drElement[0] = 23;
    drElement[1] = "V";
    drElement[2] = "Vanadium";
    drElement[3] = 50.9415f;
    dtElements.Rows.InsertAt(drElement, 2);
    dtElements.Rows[1].AcceptChanges();
}

@{
    int i = 0;
    
    <table border="5">
        <tr>
            <td><b>Atomic #</b></td>
            <td><b>Symbol</b></td>
            <td><b>Element Name</b></td>
            <td><b>Atomic Weight</b></td>
        </tr>
    @while (i < dtElements.Rows.Count)
    {
        drElement = dtElements.Rows[i];
        
        <tr>
            <td>@drElement[0]</td>
            <td>@drElement[1]</td>
            <td>@drElement[2]</td>
            <td>@drElement[3]</td>
        </tr>

        i++;
    }
    </table>
}
</body>
</html>

Rejecting Record Changes

On the other hand, if you find out that the change that is about to occur on a record should not be validated, you can cancel it. To support this, the DataRow class is equipped with a method named RejectChanges. Its syntax is:

public void RejectChanges();

Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry: Periodic Table</title>
</head>
<body>
<h1>Chemistry</h1>
<h2>Periodic Table</h2>

@{
    System.Data.DataTable dtElements = new System.Data.DataTable("element");

    dtElements.Columns.Add("atomic-number", Type.GetType("System.Int16"));
    dtElements.Columns.Add("symbol", Type.GetType("System.String"));
    dtElements.Columns.Add("element-name", Type.GetType("System.String"));
    dtElements.Columns.Add("atomic-weight", Type.GetType("System.Single"));

    System.Data.DataSet dsChemistry = new System.Data.DataSet("chemistry");
    dsChemistry.Tables.Add(dtElements);

    System.Data.DataRow drElement = dtElements.NewRow();

    drElement[0] = 21;
    drElement[1] = "Sc";
    drElement[2] = "Scandium";
    drElement[3] = 44.955908f;
    dtElements.Rows.InsertAt(drElement, 0);

    drElement = dtElements.NewRow();

    drElement[0] = 22;
    drElement[1] = "Ti";
    drElement[2] = "Titanium";
    drElement[3] = 47.867f;
    dtElements.Rows.InsertAt(drElement, 1);
    dtElements.Rows[1].RejectChanges();

    drElement = dtElements.NewRow();

    drElement[0] = 23;
    drElement[1] = "V";
    drElement[2] = "Vanadium";
    drElement[3] = 50.9415f;
    dtElements.Rows.InsertAt(drElement, 2);
    dtElements.Rows[1].AcceptChanges();
}

@{
    int i = 0;
    
    <table border="5">
        <tr>
            <td><b>Atomic #</b></td>
            <td><b>Symbol</b></td>
            <td><b>Element Name</b></td>
            <td><b>Atomic Weight</b></td>
        </tr>
    @while (i < dtElements.Rows.Count)
    {
        drElement = dtElements.Rows[i];
        
        <tr>
            <td>@drElement[0]</td>
            <td>@drElement[1]</td>
            <td>@drElement[2]</td>
            <td>@drElement[3]</td>
        </tr>

        i++;
    }
    </table>
}
</body>
</html>

This would produce:

Accept or Reject Changes

Notice that, although 4 records were created, one was rejected. After editing a record and indicating that you have accepted the changes, the record's status can receive a new status such as DataRowState.Added or DataRowState.Modified. This means that you can then call either the DataRow.SetAdded() or the DataRow.Setmodified() method.

The Nullity of a Value

As we know already, a record can contain one or more values. Each value is identified by the column to which it belongs. A column is said to be null if it does not have a value. To let you find out whether the value of a column is null, the DataRow class is equipped with a method named IsNull method. It comes in various versions. To specify the column whose value you want to check, you can pass the object name, the index, or the variable name of the column as argument.

Deleting Records

Deleting the Current Row

If you have a record you don't need, you can remove it from your table. To support the ability to remove a record, the DataRow class is equipped with a method named Delete. Its syntax is:

public void Delete();

To programmatically delete a record, first locate it by its index, get a DataRow reference to the record to be removed, and then call the Delete() method on it. Once again, you would need a way to uniquely identify a record.

Removing a Row From a Collection of Records

Besides the DataRow class, the DataRowCollection class provides its own means of deleting a record from a table. To delete a record, you can call the DataRowCollection.Remove() method. Its syntax is:

public void Remove(DataRow row);

This method takes as argument a DataRow object and checks whether the table contains it. If that record exists, it gets deleted, including all of its entries for each column.

Practical LearningPractical Learning: Deleting a Record

  1. In the Solution Explorer, below Controllers, double-click GasMetersController.cs
  2. Change the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasMetersController : Controller
        {
            private readonly DataColumn dcMake;
            private readonly DataColumn dcModel;
            private readonly DataColumn dcGasMeterID;
            private readonly DataColumn dcMeterNumber;
            private readonly DataColumn dcCounterValue;
            private readonly DataColumn dcMeterReadingDate;
    
            public DataTable dtGasMeters;
            public DataSet dsGasMeters;
    
            public GasMetersController()
            {
                dcGasMeterID = new DataColumn("gas-meter-id");
                dcGasMeterID.AutoIncrement = true;
                dcGasMeterID.AutoIncrementSeed = 1;
                dcGasMeterID.AutoIncrementStep = 1;
    
                dcMeterNumber = new DataColumn("meter-number");
                dcMeterNumber.Unique = true;
                dcMeterNumber.DataType = Type.GetType("System.String");
    
                dcMake = new DataColumn("make");
                dcMake.DataType = Type.GetType("System.String");
    
                dcModel = new DataColumn("model");
                dcModel.DataType = Type.GetType("System.String");
    
                dcMeterReadingDate = new DataColumn("meter-reading-date", Type.GetType("System.DateTime"));
    
                dcCounterValue = new DataColumn("counter-value");
                dcCounterValue.DataType = Type.GetType("System.Int32");
    
                dtGasMeters = new DataTable("gas-meter");
    
                dtGasMeters.Columns.Add(dcGasMeterID);
                dtGasMeters.Columns.Add(dcMeterNumber);
                dtGasMeters.Columns.Add(dcMake);
                dtGasMeters.Columns.Add(dcModel);
                dtGasMeters.Columns.Add(dcMeterReadingDate);
                dtGasMeters.Columns.Add(dcCounterValue);
    
                // dtGasMeters.PrimaryKey = new DataColumn[] { dtGasMeters.Columns["gas-meter-id"] };
    
                dsGasMeters = new DataSet("gas-meters");
                dsGasMeters.Tables.Add(dtGasMeters);
            }
    
            // GET: GasMeters
            public ActionResult Index()
            {
                // We will store our files in a custom folder named GasDistribution.
                // The records for gas meters are stored in an XML file named GasMeters.xml.
                // Get a reference to the file that contains records.
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                // Check whether a file for gas meters was previously created.
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    // If the file exists already, open it ...
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // ... and store the records in the appropriate data set
                        dsGasMeters.ReadXml(fsGasMeters);
                    }
                }
    
                // Prepare to use the list of records in a webpage.
                ViewBag.GasMeters = dsGasMeters.Tables[0].Rows;
                return View();
            }
    
            // GET: GasMeters/Details/5
            public ActionResult Details(int id)
            {
                // DataRow drCustomerMeter = null;
                DataRow drCustomerMeter = null;
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // Open the list of records and store them in a data set
                        dsGasMeters.ReadXml(fsGasMeters);
    
                        // Check each record
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            // Look for a Gas Meter ID that has the same value as the argument to the current method
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                // If you find such a record, get its reference
                                drCustomerMeter = drGasMeter;
                            }
                        }
                    }
                }
    
                // Send the record to the view
                ViewBag.GasMeter = drCustomerMeter;
                /* string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasMeters.ReadXml(fsGasMeters);
    
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                drCustomerMeter = drGasMeter;
                            }
                        } 
                    }
                }
    
                ViewBag.GasMeter = dsGasMeters.Tables[0].Rows.Find(id);*/ // drCustomerMeter;
                return View();
            }
    
            // GET: GasMeters/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: GasMeters/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    if (!string.IsNullOrEmpty(collection["MeterNumber"]))
                    {
                        if (System.IO.File.Exists(strGasMetersFile))
                        {
                            using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                // Get the list of gas meters and store it in the data set
                                dsGasMeters.ReadXml(fsGasMeters);
                            }
                        }
    
                        // Prepare to create a new record
                        DataRow drGasMeter = dtGasMeters.NewRow();
    
                        // Specify the value for each column using the values of the controls from the form
                        drGasMeter["meter-number"]       = collection["MeterNumber"];
                        drGasMeter["make"]               = collection["Make"];
                        drGasMeter["model"]              = collection["Model"];
                        drGasMeter["meter-reading-date"] = collection["MeterReadingDate"];
                        drGasMeter["counter-value"]      = collection["CounterValue"];
    
                        // Add the new record to the data table
                        dtGasMeters.Rows.Add(drGasMeter);
    
                        // Save the record
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            dsGasMeters.WriteXml(fsGasMeters);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: GasMeters/Edit/5
            public ActionResult Edit(int id)
            {
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // If a file for the records of gas meters exists, open it and store the records in the data set.
                        dsGasMeters.ReadXml(fsGasMeters);
    
                        // Check each record.
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                /* If you find a gas meter that has the same Gas Meter ID 
                                 * as the value passed as argument, send that record to the view. */
                                ViewBag.GasMeter = drGasMeter;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: GasMeters/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    if (System.IO.File.Exists(strGasMetersFile))
                    {
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            /* Get a list of gas meters and store them in a data set. */
                            dsGasMeters.ReadXml(fsGasMeters);
                        }
                    }
    
                    // Get ready to update a record of gas meters
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        // Check each gas meter record
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            // If you find a gas meter that has the same Gas Meter ID as the argument, ...
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                // ..., get ready to update the record
                                drGasMeter.BeginEdit();
                                // Change/Specify the value of each column based on the corresponding column of the table
                                drGasMeter["meter-number"]       = collection["MeterNumber"];
                                drGasMeter["make"]               = collection["Make"];
                                drGasMeter["model"]              = collection["Model"];
                                drGasMeter["meter-reading-date"] = collection["MeterReadingDate"];
                                drGasMeter["counter-value"]      = collection["CounterValue"];
                                // Stop editing the record
                                drGasMeter.EndEdit();
    
                                // Save the edited record
                                dsGasMeters.WriteXml(fsGasMeters);
    
                                // If you had found, and then edited, the record, stop checking
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: GasMeters/Delete/5
            public ActionResult Delete(int id)
            {
                string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                // Check whether a file for a list of records exists already
                if (System.IO.File.Exists(strGasMetersFile))
                {
                    // If the file exists, get ready to open it
                    using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // Store the list of records in the data set.
                        dsGasMeters.ReadXml(fsGasMeters);
    
                        // Check each record
                        foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                        {
                            // If you find a record that has the same Gas Meter ID as the argument, ...
                            if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                            {
                                // Get each value of the record and send it to the view
                                ViewBag.GasMeterID       = drGasMeter["gas-meter-id"];
                                ViewBag.MeterNumber      = drGasMeter["meter-number"];
                                ViewBag.Make             = drGasMeter["make"];
                                ViewBag.Model            = drGasMeter["model"];
                                ViewBag.MeterReadingDate = DateTime.Parse(drGasMeter["meter-reading-date"].ToString()).ToLongDateString();
                                ViewBag.CounterValue     = drGasMeter["counter-value"];
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: GasMeters/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    // Check whether a file for gas meters was already created
                    if (System.IO.File.Exists(strGasMetersFile))
                    {
                        // If so, open it, ...
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open,
                                                                       FileAccess.Read, FileShare.Read))
                        {
                            // ... and store it in a data set
                            dsGasMeters.ReadXml(fsGasMeters);
    
                            // Check each gas meter record
                            foreach (DataRow drGasMeter in dsGasMeters.Tables[0].Rows)
                            {
                                // If you find a gas meter record that the same Gas Meter ID as the argument, ...
                                if (int.Parse(drGasMeter["gas-meter-id"].ToString()) == id)
                                {
                                    // ... delelete it, ...
                                    dsGasMeters.Tables[0].Rows.Remove(drGasMeter);
                                    break;
                                }
                            }
                        }
    
                        // ... and save the file
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Create,
                                                                       FileAccess.Write, FileShare.Write))
                        {
                            dsGasMeters.WriteXml(fsGasMeters);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  3. Right-click inside any of the Delete() methods and click Add View...
  4. Make sure the View Name text box has Delete.
    Make sure the Use A Layout Page text box contains ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  5. Change the code of the webpage as follows:
    @{
        ViewBag.Title = "Delete Gas Meter";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Delete Gas Meter</h2>
    
    <hr />
    
    <h3 class="common-font blue">Are you sure you want to remove this gas meter from the database?</h3>
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="medium bold">Gas Meter ID:</td>
                <td>@ViewBag.GasMeterID</td>
            </tr>
            <tr>
                <td class="bold">Meter #:</td>
                <td>@ViewBag.MeterNumber</td>
            </tr>
            <tr>
                <td class="bold">Make:</td>
                <td>@ViewBag.Make</td>
            </tr>
            <tr>
                <td class="bold">Model:</td>
                <td>@ViewBag.Model</td>
            </tr>
            <tr>
                <td class="bold">Meter Reading Date:</td>
                <td>@ViewBag.MeterReadingDate</td>
            </tr>
            <tr>
                <td class="bold">Counter Value:</td>
                <td>@ViewBag.CounterValue</td>
            </tr>
        </table>
        <hr />
        @using (Html.BeginForm())
        {
            <div>
                <input type="submit" value="Remove this Gas Meter" class="btn btn-warning" /> ::
                <a class="btn btn-warning" href="/GasMeters/Index">Gas Meters</a>
            </div>
        }
    </div>
  6. In the Solution Explorer, under Controllers, double-click CustomersController.cs
  7. Change the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class CustomersController : Controller
        {
            private readonly DataColumn dcCity;
            private readonly DataColumn dcState;
            private readonly DataColumn dcCounty;
            private readonly DataColumn dcZIPCode;
            private readonly DataColumn dcAddress;
            private readonly DataColumn dcLastName;
            private readonly DataColumn dcFirstName;
            private readonly DataColumn dcCustomerID;
            private readonly DataColumn dcMeterNumber;
            private readonly DataColumn dcAccountNumber;
    
            public DataTable dtCustomers;
            public DataSet dsCustomers;
    
            public CustomersController()
            {
                dcCustomerID = new DataColumn("customer-id")
                {
                    AutoIncrement = true,
                    AutoIncrementSeed = 1,
                    AutoIncrementStep = 1
                };
    
                dcCity = new DataColumn("city", Type.GetType("System.String"));
                dcState = new DataColumn("state", Type.GetType("System.String"));
                dcCounty = new DataColumn("county", Type.GetType("System.String"));
                dcAddress = new DataColumn("address", Type.GetType("System.String"));
                dcZIPCode = new DataColumn("zip-code", Type.GetType("System.String"));
                dcLastName = new DataColumn("last-name", Type.GetType("System.String"));
                dcFirstName = new DataColumn("first-name", Type.GetType("System.String"));
                dcMeterNumber = new DataColumn("meter-number", Type.GetType("System.String"));
                dcAccountNumber = new DataColumn("account-number", Type.GetType("System.String"))
                {
                    Unique = true
                };
    
                dtCustomers = new DataTable("customer");
    
                dtCustomers.Columns.Add(dcCustomerID);
                dtCustomers.Columns.Add(dcAccountNumber);
                dtCustomers.Columns.Add(dcMeterNumber);
                dtCustomers.Columns.Add(dcFirstName);
                dtCustomers.Columns.Add(dcLastName);
                dtCustomers.Columns.Add(dcAddress);
                dtCustomers.Columns.Add(dcCity);
                dtCustomers.Columns.Add(dcCounty);
                dtCustomers.Columns.Add(dcState);
                dtCustomers.Columns.Add(dcZIPCode);
    
                dsCustomers = new DataSet("customers");
                dsCustomers.Tables.Add(dtCustomers);
            }
    
            // GET: Customers
            public ActionResult Index()
            {
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsCustomers);
                    }
                }
    
                ViewBag.Customers = dsCustomers.Tables[0].Rows;
                return View();
            }
    
            // GET: Customers/Details/5
            public ActionResult Details(int id)
            {
                DataRow drCustomer = null;
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsGasMeters = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsGasMeters);
    
                        foreach (DataRow drClient in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drClient["customer-id"].ToString()) == id)
                            {
                                drCustomer = drClient;
                            }
                        }
                    }
                }
    
                ViewBag.Customer = drCustomer;
                return View();
            }
    
            // GET: Customers/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Customers/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    GasMetersController gasMtrCtrlr = new GasMetersController();
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                    // We want to make sure the user provides an account number for the customer
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        // If that's the case, check whether an XML file for customers was previously created
                        if (System.IO.File.Exists(strCustomersFile))
                        {
                            // If there is such a file, open it ...
                            using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                // and store the list of customers in the Customers data set
                                dsCustomers.ReadXml(fsCustomers);
                            }
                        }
    
                        // Since we have all the necessary information, let's create a record
                        DataRow drCustomer = dtCustomers.NewRow();
    
                        drCustomer["account-number"] = collection["AccountNumber"];
                        drCustomer["meter-number"]   = collection["MeterNumber"];
                        drCustomer["first-name"]     = collection["FirstName"];
                        drCustomer["last-name"]      = collection["LastName"];
                        drCustomer["address"]        = collection["Address"];
                        drCustomer["city"]           = collection["City"];
                        drCustomer["county"]         = collection["County"];
                        drCustomer["state"]          = collection["State"];
                        drCustomer["zip-code"]       = collection["ZIPCode"];
    
                        dtCustomers.Rows.Add(drCustomer);
    
                        // Save the record
                        using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                        {
                            dsCustomers.WriteXml(fsCustomers);
                        }
                    }
    
                    // Return the user to the list of customers
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Customers/Edit/5
            public ActionResult Edit(int id)
            {
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsCustomers);
    
                        foreach (DataRow drCustomer in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drCustomer["customer-id"].ToString()) == id)
                            {
                                ViewBag.Customer = drCustomer;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Customers/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                    if (System.IO.File.Exists(strCustomersFile))
                    {
                        using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsCustomers.ReadXml(fsCustomers);
                        }
                    }
    
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drCustomer in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drCustomer["customer-id"].ToString()) == id)
                            {
                                drCustomer.BeginEdit();
                                drCustomer["account-number"] = collection["AccountNumber"];
                                drCustomer["meter-number"]   = collection["MeterNumber"];
                                drCustomer["first-name"]     = collection["FirstName"];
                                drCustomer["last-name"]      = collection["LastName"];
                                drCustomer["address"]        = collection["Address"];
                                drCustomer["city"]           = collection["City"];
                                drCustomer["county"]         = collection["County"];
                                drCustomer["state"]          = collection["State"];
                                drCustomer["zip-code"]       = collection["ZIPCode"];
                                drCustomer.EndEdit();
    
                                dsCustomers.WriteXml(fsCustomers);
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Customers/Delete/5
            public ActionResult Delete(int id)
            {
                string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strCustomersFile))
                {
                    using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsCustomers.ReadXml(fsCustomers);
    
                        foreach (DataRow drCustomer in dsCustomers.Tables[0].Rows)
                        {
                            if (int.Parse(drCustomer["customer-id"].ToString()) == id)
                            {
                                ViewBag.CustomerID    = drCustomer["customer-id"];
                                ViewBag.AccountNumber = drCustomer["account-number"];
                                ViewBag.MeterNumber   = drCustomer["meter-number"];
                                ViewBag.FirstName     = drCustomer["first-name"];
                                ViewBag.LastName      = drCustomer["last-name"];
                                ViewBag.Address       = drCustomer["address"];
                                ViewBag.City          = drCustomer["city"];
                                ViewBag.County        = drCustomer["county"];
                                ViewBag.State         = drCustomer["state"];
                                ViewBag.ZIPCode       = drCustomer["zip-code"];
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Customers/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
    
                    if (System.IO.File.Exists(strCustomersFile))
                    {
                        using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Open,
                                                                       FileAccess.Read, FileShare.Read))
                        {
                            dsCustomers.ReadXml(fsCustomers);
    
                            foreach (DataRow drCustomer in dsCustomers.Tables[0].Rows)
                            {
                                if (int.Parse(drCustomer["customer-id"].ToString()) == id)
                                {
                                    dsCustomers.Tables[0].Rows.Remove(drCustomer);
                                    break;
                                }
                            }
                        }
    
                        using (FileStream fsCustomers = new FileStream(strCustomersFile, FileMode.Create,
                                                                       FileAccess.Write, FileShare.Write))
                        {
                            dsCustomers.WriteXml(fsCustomers);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  8. Right-click one of the Delete() lines and click Add View...
  9. In the Add View dialog box, make sure the View Name text box is displaying Delete.
    Make sure the Use A Layout Page text box contains ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  10. Change the code as follows:
    @{
        ViewBag.Title = "Delete Customer Account";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Delete Customer Account</h2>
    
    <hr />
    
    <h3 class="common-font blue">Are you sure you want to delete the account of this customer?</h3>
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="medium bold">Customer ID:</td>
                <td>@ViewBag.CustomerID</td>
            </tr>
            <tr>
                <td class="bold">Account #:</td>
                <td>@ViewBag.AccountNumber</td>
            </tr>
            <tr>
                <td class="bold">Meter #:</td>
                <td>@ViewBag.MeterNumber</td>
            </tr>
            <tr>
                <td class="bold">First Name:</td>
                <td>@ViewBag.FirstName</td>
            </tr>
            <tr>
                <td class="bold">Last Name:</td>
                <td>@ViewBag.LastName</td>
            </tr>
            <tr>
                <td class="bold">Address:</td>
                <td>@ViewBag.Address</td>
            </tr>
            <tr>
                <td class="bold">City:</td>
                <td>@ViewBag.City</td>
            </tr>
            <tr>
                <td class="bold">County:</td>
                <td>@ViewBag.County</td>
            </tr>
            <tr>
                <td class="bold">State:</td>
                <td>@ViewBag.State</td>
            </tr>
            <tr>
                <td class="bold">ZIP-Code:</td>
                <td>@ViewBag.ZIPCode</td>
            </tr>
        </table>
        <hr />
        @using (Html.BeginForm())
        {
            <div>
                <input type="submit" value="Delete Customer Account" class="btn btn-warning" /> ::
                <a class="btn btn-warning" href="/Customers/Index">Customers</a>
            </div>
        }
    </div>
  11. In the Solution Explorer, under Controllers, double-click GasBillsController.cs
  12. Implement the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class GasBillsController : Controller
        {
            private readonly DataColumn dcGasBillID;
            private readonly DataColumn dcAmountDue;
            private readonly DataColumn dcStateTaxes;
            private readonly DataColumn dcLocalTaxes;
            private readonly DataColumn dcConsumption;
            private readonly DataColumn dcBillingDays;
            private readonly DataColumn dcTotalTherms;
            private readonly DataColumn dcOver50Therms;
            private readonly DataColumn dcTotalCharges;
            private readonly DataColumn dcAccountNumber;
            private readonly DataColumn dcFirst50Therms;
            private readonly DataColumn dcDeliveryTotal;
            private readonly DataColumn dcLateAmountDue;
            private readonly DataColumn dcPaymentDueDate;
            private readonly DataColumn dcCounterReadingEnd;
            private readonly DataColumn dcCounterReadingStart;
            private readonly DataColumn dcMeterReadingEndDate;
            private readonly DataColumn dcEnvironmentalCharges;
            private readonly DataColumn dcMeterReadingStartDate;
            private readonly DataColumn dcTransportationCharges;
            private readonly DataColumn dcDistributionAdjustment;
    
            public DataTable dtGasBills;
            private DataSet dsGasBills;
    
            public GasBillsController()
            {
                dcGasBillID = new DataColumn("gas-bill-id")
                {
                    AutoIncrement = true,
                    AutoIncrementSeed = 1,
                    AutoIncrementStep = 1
                };
    
                dcAmountDue = new DataColumn("amount-due", Type.GetType("System.Decimal"));
                dcConsumption = new DataColumn("consumption", Type.GetType("System.Int32"));
                dcBillingDays = new DataColumn("billing-days", Type.GetType("System.Int32"));
                dcLocalTaxes = new DataColumn("local-taxes", Type.GetType("System.Decimal"));
                dcStateTaxes = new DataColumn("state-taxes", Type.GetType("System.Decimal"));
                dcTotalTherms = new DataColumn("total-therms", Type.GetType("System.String"));
                dcTotalCharges = new DataColumn("total-charges", Type.GetType("System.Decimal"));
                dcAccountNumber = new DataColumn("account-number", Type.GetType("System.String"));
                dcOver50Therms = new DataColumn("over-50-therms", Type.GetType("System.Decimal"));
                dcDeliveryTotal = new DataColumn("delivery-total", Type.GetType("System.Decimal"));
                dcFirst50Therms = new DataColumn("first-50-therms", Type.GetType("System.Decimal"));
                dcLateAmountDue = new DataColumn("late-amount-due", Type.GetType("System.Decimal"));
                dcPaymentDueDate = new DataColumn("payment-due-date", Type.GetType("System.DateTime"));
                dcCounterReadingEnd = new DataColumn("counter-reading-end", Type.GetType("System.Int32"));
                dcCounterReadingStart = new DataColumn("counter-reading-start", Type.GetType("System.Int32"));
                dcEnvironmentalCharges = new DataColumn("environmental-charges", Type.GetType("System.Decimal"));
                dcMeterReadingEndDate = new DataColumn("meter-reading-end-date", Type.GetType("System.DateTime"));
                dcTransportationCharges = new DataColumn("transportation-charges", Type.GetType("System.Decimal"));
                dcDistributionAdjustment = new DataColumn("distribution-adjustment", Type.GetType("System.Decimal"));
                dcMeterReadingStartDate = new DataColumn("meter-reading-start-date", Type.GetType("System.DateTime"));
    
                dtGasBills = new DataTable("gas-bill");
    
                dtGasBills.Columns.Add(dcGasBillID);
                dtGasBills.Columns.Add(dcAccountNumber);
                dtGasBills.Columns.Add(dcMeterReadingStartDate);
                dtGasBills.Columns.Add(dcMeterReadingEndDate);
                dtGasBills.Columns.Add(dcBillingDays);
                dtGasBills.Columns.Add(dcCounterReadingStart);
                dtGasBills.Columns.Add(dcCounterReadingEnd);
                dtGasBills.Columns.Add(dcConsumption);
                dtGasBills.Columns.Add(dcTotalTherms);
                dtGasBills.Columns.Add(dcTransportationCharges);
                dtGasBills.Columns.Add(dcFirst50Therms);
                dtGasBills.Columns.Add(dcOver50Therms);
                dtGasBills.Columns.Add(dcDeliveryTotal);
                dtGasBills.Columns.Add(dcDistributionAdjustment);
                dtGasBills.Columns.Add(dcEnvironmentalCharges);
                dtGasBills.Columns.Add(dcTotalCharges);
                dtGasBills.Columns.Add(dcLocalTaxes);
                dtGasBills.Columns.Add(dcStateTaxes);
                dtGasBills.Columns.Add(dcPaymentDueDate);
                dtGasBills.Columns.Add(dcAmountDue);
                dtGasBills.Columns.Add(dcLateAmountDue);
    
                dsGasBills = new DataSet("gas-bills");
                dsGasBills.Tables.Add(dtGasBills);
            }
    
            // GET: GasBills
            public ActionResult Index()
            {
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
                    }
                }
    
                ViewBag.GasBills = dsGasBills.Tables[0].Rows;
                return View();
            }
    
            // GET: GasBills/Details/5
            public ActionResult Details(int id)
            {
                DataRow drGasBill = null;
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
    
                        foreach (DataRow drClient in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drClient["gas-bill-id"].ToString()) == id)
                            {
                                drGasBill= drClient;
                            }
                        }
                    }
                }
    
                ViewBag.Invoice = drGasBill;
                return View();
            }
    
            // GET: GasBills/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: GasBills/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    string meterNumber = string.Empty;
                    string accountNumber = string.Empty;
                    // We will need all three files
                    string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
                    string strCustomersFile = Server.MapPath("/GasDistribution/Customers.xml");
                    string strGasMetersFile = Server.MapPath("/GasDistribution/GasMeters.xml");
    
                    // Make sure the user provided an account number for the customer
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        // If that's the case, check whether a file for customers was previously created
                        if (System.IO.File.Exists(strGasBillsFile))
                        {
                            // If there is such a file, open it ...
                            using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                // and store the list of invoices in the gas bills data set
                                dsGasBills.ReadXml(fsGasBills);
                            }
                        }
    
                        // Based on the provided information for an invoice, prepare to issue a gas bill
                        DataRow drGasBill = dtGasBills.NewRow();
    
                        // We will need the customer account number for a later operation
                        accountNumber = collection["AccountNumber"];
    
                        // Specify the value of each column
                        drGasBill["account-number"] = collection["AccountNumber"];
                        drGasBill["meter-reading-start-date"] = collection["MeterReadingStartDate"];
                        drGasBill["meter-reading-end-date"] = collection["MeterReadingEndDate"];
                        drGasBill["billing-days"] = collection["BillingDays"];
                        drGasBill["counter-reading-start"] = collection["CounterReadingStart"];
                        drGasBill["counter-reading-end"] = collection["CounterReadingEnd"];
                        drGasBill["consumption"] = collection["Consumption"];
                        drGasBill["total-therms"] = collection["TotalTherms"];
                        drGasBill["transportation-charges"] = collection["TransportationCharges"];
                        drGasBill["first-50-therms"] = collection["First50Therms"];
                        drGasBill["over-50-therms"] = collection["Over50Therms"];
                        drGasBill["delivery-total"] = collection["DeliveryTotal"];
                        drGasBill["distribution-adjustment"] = collection["DistributionAdjustment"];
                        drGasBill["environmental-charges"] = collection["EnvironmentalCharges"];
                        drGasBill["total-charges"] = collection["TotalCharges"];
                        drGasBill["local-taxes"] = collection["LocalTaxes"];
                        drGasBill["state-taxes"] = collection["StateTaxes"];
                        drGasBill["payment-due-date"] = collection["PaymentDueDate"];
                        drGasBill["amount-due"] = collection["AmountDue"];
                        drGasBill["late-amount-due"] = collection["LateAmountDue"];
                        // Add the gas bill to the data table
                        dtGasBills.Rows.Add(drGasBill);
    
                        // Save the gas bill
                        using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                        {
                            dsGasBills.WriteXml(fsGasBills);
                        }
    
                        // When a gas bill has been issued, we want to updat the customer's gas meter (this is not necessary, just a convenience).
                        /* To start, we want to know the gas meter used by the customer. 
                         * The gas meter number can be found in the customer account. */
                        // A table for customers was created in its controller
                        CustomersController clientController = new CustomersController();
    
                        // Open the file that contains the customers record, ...
                        if (System.IO.File.Exists(strCustomersFile))
                        {
                            using (FileStream fsGasMeters = new FileStream(strCustomersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                clientController.dsCustomers.ReadXml(fsGasMeters);
    
                                // ... and locate the customer account number
                                foreach (DataRow drClient in clientController.dsCustomers.Tables[0].Rows)
                                {
                                    if (drClient["account-number"].ToString() == accountNumber)
                                    {
                                        // Get the meter number used by the customer
                                        meterNumber = drClient["meter-number"].ToString();
                                    }
                                }
                            }
                        }
    
                        // Now that we have the meter number, let's get the gas meter record.
                        // The table of gas meters was created in its controller
                        GasMetersController gmc = new GasMetersController();
    
                        if (System.IO.File.Exists(strGasMetersFile))
                        {
                            using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                /* Get a list of gas meters and store them in a data set. */
                                gmc.dsGasMeters.ReadXml(fsGasMeters);
                            }
                        }
    
                        // Get ready to update a record of gas meters
                        using (FileStream fsGasMeters = new FileStream(strGasMetersFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            // Check each gas meter record
                            foreach (DataRow drGasMeter in gmc.dsGasMeters.Tables[0].Rows)
                            {
                                // If you find a gas meter that has the meter number found above, ...
                                if (drGasMeter["meter-number"].ToString() == meterNumber)
                                {
                                    drGasMeter.BeginEdit();
                                    // Change the value of the meter reading date...
                                    drGasMeter["meter-reading-date"] = collection["MeterReadingEndDate"];
                                    // ... and the counter value
                                    drGasMeter["counter-value"] = collection["CounterReadingEnd"];
                                    drGasMeter.EndEdit();
    
                                    // Save the edited record
                                    gmc.dsGasMeters.WriteXml(fsGasMeters);
    
                                    // If you had found, and then edited, the record, stop checking
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: GasBills/Edit/5
            public ActionResult Edit(int id)
            {
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
    
                        foreach (DataRow drGasBill in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drGasBill["gas-bill-id"].ToString()) == id)
                            {
                                ViewBag.GasBill = drGasBill;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: GasBills/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                    if (System.IO.File.Exists(strGasBillsFile))
                    {
                        using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsGasBills.ReadXml(fsGasBills);
                        }
                    }
    
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drGasBill in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drGasBill["gas-bill-id"].ToString()) == id)
                            {
                                drGasBill.BeginEdit();
                                drGasBill["account-number"] = collection["AccountNumber"];
                                drGasBill["meter-reading-start-date"] = collection["MeterReadingStartDate"];
                                drGasBill["meter-reading-end-date"] = collection["MeterReadingEndDate"];
                                drGasBill["billing-days"] = collection["BillingDays"];
                                drGasBill["counter-reading-start"] = collection["CounterReadingStart"];
                                drGasBill["counter-reading-end"] = collection["CounterReadingEnd"];
                                drGasBill["consumption"] = collection["Consumption"];
                                drGasBill["total-therms"] = collection["TotalTherms"];
                                drGasBill["transportation-charges"] = collection["TransportationCharges"];
                                drGasBill["first-50-therms"] = collection["First50Therms"];
                                drGasBill["over-50-therms"] = collection["Over50Therms"];
                                drGasBill["delivery-total"] = collection["DeliveryTotal"];
                                drGasBill["distribution-adjustment"] = collection["DistributionAdjustment"];
                                drGasBill["environmental-charges"] = collection["EnvironmentalCharges"];
                                drGasBill["total-charges"] = collection["TotalCharges"];
                                drGasBill["local-taxes"] = collection["LocalTaxes"];
                                drGasBill["state-taxes"] = collection["StateTaxes"];
                                drGasBill["payment-due-date"] = collection["PaymentDueDate"];
                                drGasBill["amount-due"] = collection["AmountDue"];
                                drGasBill["late-amount-due"] = collection["LateAmountDue"];
                                drGasBill.EndEdit();
    
                                dsGasBills.WriteXml(fsGasBills);
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: GasBills/Delete/5
            public ActionResult Delete(int id)
            {
                string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                if (System.IO.File.Exists(strGasBillsFile))
                {
                    using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsGasBills.ReadXml(fsGasBills);
    
                        foreach (DataRow drGasBill in dsGasBills.Tables[0].Rows)
                        {
                            if (int.Parse(drGasBill["gas-bill-id"].ToString()) == id)
                            {
                                ViewBag.GasBillID = drGasBill["gas-bill-id"];
                                ViewBag.AccountNumber = drGasBill["account-number"];
                                ViewBag.MeterReadingStartDate = DateTime.Parse(drGasBill["meter-reading-start-date"].ToString()).ToLongDateString();
                                ViewBag.MeterReadingEndDate = DateTime.Parse(drGasBill["meter-reading-end-date"].ToString()).ToLongDateString();
                                ViewBag.BillingDays = drGasBill["billing-days"];
                                ViewBag.CounterReadingStart = drGasBill["counter-reading-start"];
                                ViewBag.CounterReadingEnd = drGasBill["counter-reading-end"];
                                ViewBag.Consumption = drGasBill["consumption"];
                                ViewBag.TotalTherms = drGasBill["total-therms"];
                                ViewBag.TransportationCharges = drGasBill["transportation-charges"];
                                ViewBag.First50Therms = drGasBill["first-50-therms"];
                                ViewBag.Over50Therms = drGasBill["over-50-therms"];
                                ViewBag.DeliveryTotal = drGasBill["delivery-total"];
                                ViewBag.DistributionAdjustment = drGasBill["distribution-adjustment"];
                                ViewBag.EnvironmentalCharges = drGasBill["environmental-charges"];
                                ViewBag.TotalCharges = drGasBill["total-charges"];
                                ViewBag.LocalTaxes = drGasBill["local-taxes"];
                                ViewBag.StateTaxes = drGasBill["state-taxes"];
                                ViewBag.PaymentDueDate = DateTime.Parse(drGasBill["payment-due-date"].ToString()).ToLongDateString();
                                ViewBag.AmountDue = drGasBill["amount-due"];
                                ViewBag.LateAmountDue = drGasBill["late-amount-due"];
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: GasBills/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    string strGasBillsFile = Server.MapPath("/GasDistribution/GasBills.xml");
    
                    if (System.IO.File.Exists(strGasBillsFile))
                    {
                        using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Open,
                                                                       FileAccess.Read, FileShare.Read))
                        {
                            dsGasBills.ReadXml(fsGasBills);
    
                            foreach (DataRow drGasBill in dsGasBills.Tables[0].Rows)
                            {
                                if (int.Parse(drGasBill["gas-bill-id"].ToString()) == id)
                                {
                                    dsGasBills.Tables[0].Rows.Remove(drGasBill);
                                    break;
                                }
                            }
                        }
    
                        using (FileStream fsGasBills = new FileStream(strGasBillsFile, FileMode.Create,
                                                                       FileAccess.Write, FileShare.Write))
                        {
                            dsGasBills.WriteXml(fsGasBills);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  13. Right-click one of the Delete() lines and click Add View...
  14. In the Add View dialog box, make sure the View Name text box is displaying Delete.
    Make sure the Use A Layout Page text box contains ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  15. Change the code as follows:
    @{
        ViewBag.Title = "Deleting Gas Bill";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    }
    
    <h2 class="text-center common-font bold">Cancelling Gas Bill</h2>
    
    <hr />
    
    <h3 class="common-font blue">Are you sure you want to cancel this gas bill?</h3>
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="large bold">Gas Bill ID:</td>
                <td>@ViewBag.GasBillID</td>
            </tr>
            <tr>
                <td class="bold">Account #:</td>
                <td>@ViewBag.AccountNumber</td>
            </tr>
            <tr>
                <td class="bold">Meter Reading Start Date:</td>
                <td>@ViewBag.MeterReadingStartDate</td>
            </tr>
            <tr>
                <td class="bold">Meter Reading End Date:</td>
                <td>@ViewBag.MeterReadingEndDate</td>
            </tr>
            <tr>
                <td class="bold">Billing Days:</td>
                <td>@ViewBag.BillingDays</td>
            </tr>
            <tr>
                <td class="bold">Counter Reading Start:</td>
                <td>@ViewBag.CounterReadingStart</td>
            </tr>
            <tr>
                <td class="bold">Counter Reading End:</td>
                <td>@ViewBag.CounterReadingEnd</td>
            </tr>
            <tr>
                <td class="bold">Consumption:</td>
                <td>@ViewBag.Consumption</td>
            </tr>
            <tr>
                <td class="bold">Total Therms:</td>
                <td>@ViewBag.TotalTherms</td>
            </tr>
            <tr>
                <td class="bold">Transportation Charges:</td>
                <td>@ViewBag.TransportationCharges</td>
            </tr>
            <tr>
                <td class="bold">First 50 Therms:</td>
                <td>@ViewBag.First50Therms</td>
            </tr>
            <tr>
                <td class="bold">Over 50 Therms:</td>
                <td>@ViewBag.Over50Therms</td>
            </tr>
            <tr>
                <td class="bold">Delivery Total:</td>
                <td>@ViewBag.DeliveryTotal</td>
            </tr>
            <tr>
                <td class="bold">Distribution Adjustment:</td>
                <td>@ViewBag.DistributionAdjustment</td>
            </tr>
            <tr>
                <td class="bold">Environmental Charges:</td>
                <td>@ViewBag.EnvironmentalCharges</td>
            </tr>
            <tr>
                <td class="bold">Total Charges:</td>
                <td>@ViewBag.TotalCharges</td>
            </tr>
            <tr>
                <td class="bold">Local Taxes:</td>
                <td>@ViewBag.LocalTaxes</td>
            </tr>
            <tr>
                <td class="bold">State Taxes:</td>
                <td>@ViewBag.StateTaxes</td>
            </tr>
            <tr>
                <td class="bold">Payment Due Date:</td>
                <td>@ViewBag.PaymentDueDate</td>
            </tr>
            <tr>
                <td class="bold">Amount Due:</td>
                <td>@ViewBag.AmountDue</td>
            </tr>
            <tr>
                <td class="bold">Late Amount Due:</td>
                <td>@ViewBag.LateAmountDue</td>
            </tr>
        </table>
        <hr />
        @using (Html.BeginForm())
        {
            <div>
                <input type="submit" value="Delete this Gas Bill" class="btn btn-warning" /> ::
                <a class="btn btn-warning" href="/GasBills/Index">Customers Gas Bills</a>
            </div>
        }
    </div>
  16. In the Solution Explorer, under Controllers, double-click PaymentsController.cs
  17. Implement the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany1.Controllers
    {
        public class PaymentsController : Controller
        {
            private readonly DataColumn dcGasBillID;
            private readonly DataColumn dcPaymentID;
            private readonly DataColumn dcPaymentDate;
            private readonly DataColumn dcPaymentAmount;
            private readonly DataColumn dcPaymentStatus;
    
            private DataTable dtPayments;
            private DataSet   dsPayments;
    
            public PaymentsController()
            {
                dcPaymentID = new DataColumn("payment-id")
                {
                    AutoIncrement = true,
                    AutoIncrementSeed = 1,
                    AutoIncrementStep = 1
                };
    
                dcPaymentStatus = new DataColumn("payment-status")
                {
                    DataType = Type.GetType("System.String")
                };
                dcGasBillID     = new DataColumn("gas-bill-id", Type.GetType("System.Int32"));
                dcPaymentDate   = new DataColumn("payment-date", Type.GetType("System.DateTime"));
                dcPaymentAmount = new DataColumn("payment-amount", Type.GetType("System.Decimal"));
    
                dtPayments = new DataTable("payment");
                dtPayments.Columns.Add(dcPaymentID);
                dtPayments.Columns.Add(dcPaymentDate);
                dtPayments.Columns.Add(dcGasBillID);
                dtPayments.Columns.Add(dcPaymentAmount);
                dtPayments.Columns.Add(dcPaymentStatus);
    
                dsPayments = new DataSet("payments");
                dsPayments.Tables.Add(dtPayments);
            }
    
            // GET: Payments
            public ActionResult Index()
            {
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
                
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
                    }
                }
    
                // Prepare to use the list of records in a webpage.
                ViewBag.Payments = dsPayments.Tables[0].Rows;
                return View();
            }
    
            // GET: Payments/Details/5
            public ActionResult Details(int id)
            {
                DataRow drInvoice = null;
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
                        
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                drInvoice = drPayment;
                            }
                        }
                    }
                }
                
                ViewBag.Payment = drInvoice;
                return View();
            }
    
            // GET: Payments/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Payments/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                    if (System.IO.File.Exists(strPaymentsFile))
                    {
                        using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsPayments.ReadXml(fsPayments);
                        }
                    }
                        
                        DataRow drPayment = dtPayments.NewRow();
    
                        drPayment["payment-date"]   = collection["PaymentDate"];
                        drPayment["gas-bill-id"]    = collection["GasBillID"];
                        drPayment["payment-amount"] = collection["PaymentAmount"];
                        drPayment["payment-status"] = collection["PaymentStatus"];
                        
                        dtPayments.Rows.Add(drPayment);
                        
                        using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            dsPayments.WriteXml(fsPayments);
                        }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Payments/Edit/5
            public ActionResult Edit(int id)
            {
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
                        
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                ViewBag.Payment = drPayment;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Payments/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
    
                    if (System.IO.File.Exists(strPaymentsFile))
                    {
                        using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            dsPayments.ReadXml(fsPayments);
                        }
                    }
                    
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                drPayment.BeginEdit();
    
                                drPayment["payment-date"]   = collection["PaymentDate"];
                                drPayment["gas-bill-id"]    = collection["GasBillID"];
                                drPayment["payment-amount"] = collection["PaymentAmount"];
                                drPayment["payment-status"] = collection["PaymentStatus"];
                                
                                drPayment.EndEdit();
    
                                dsPayments.WriteXml(fsPayments);
                                
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Payments/Delete/5
            public ActionResult Delete(int id)
            {
                string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
                
                if (System.IO.File.Exists(strPaymentsFile))
                {
                    using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsPayments.ReadXml(fsPayments);
    
                        foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                        {
                            if (int.Parse(drPayment["payment-id"].ToString()) == id)
                            {
                                ViewBag.PaymentID     = drPayment["payment-id"];
                                ViewBag.PaymentDate   = DateTime.Parse(drPayment["payment-date"].ToString()).ToLongDateString();
                                ViewBag.GasBillID     = drPayment["gas-bill-id"];
                                ViewBag.PaymentAmount = drPayment["payment-amount"];
                                ViewBag.PaymentStatus = drPayment["payment-status"];
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Payments/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    string strPaymentsFile = Server.MapPath("/GasDistribution/Payments.xml");
                    
                    if (System.IO.File.Exists(strPaymentsFile))
                    {
                        using (FileStream fsPayments = new FileStream(strPaymentsFile, FileMode.Open,
                                                                      FileAccess.Read, FileShare.Read))
                        {
                            dsPayments.ReadXml(fsPayments);
                            
                            foreach (DataRow drPayment in dsPayments.Tables[0].Rows)
                            {
                                if (int.Parse(drPayment["payment-id"].ToString()) == id)
                                {
                                    dsPayments.Tables[0].Rows.Remove(drPayment);
                                    break;
                                }
                            }
                        }
    
                        using (FileStream fsPayments = new FileStream(strPaymentsFile,  FileMode.Create,
                                                                      FileAccess.Write, FileShare.Write))
                        {
                            dsPayments.WriteXml(fsPayments);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  18. Right-click one of the Delete() lines and click Add View...
  19. In the Add View dialog box, make sure the View Name text box is displaying Delete.
    Make sure the Use A Layout Page text box contains ~/Views/Shared/_Arrangement.cshtml.
    Click Add
  20. Set the webpage as follows:
    @{
        ViewBag.Title = "Delete Bill Payment";
        Layout = "~/Views/Shared/_Arrangement.cshtml";
    
        string pmtDate = DateTime.Parse(ViewBag.PaymentDate).ToLongDateString();
    }
    
    <h2 class="text-center common-font bold">Cancel Bill Payment</h2>
    
    <hr />
    
    <h3 class="common-font blue">Are you sure you want to delete/cancel this gas bill Payment?</h3>
    
    <div class="utility-container">
        <table class="common-font">
            <tr>
                <td class="medium bold">Payment ID:</td>
                <td>@ViewBag.PaymentID</td>
            </tr>
            <tr>
                <td class="bold">Payment Date:</td>
                <td>@pmtDate</td>
            </tr>
            <tr>
                <td class="bold">Gas Bill ID:</td>
                <td>@ViewBag.GasBillID</td>
            </tr>
            <tr>
                <td class="bold">Payment Amount:</td>
                <td>@ViewBag.PaymentAmount</td>
            </tr>
            <tr>
                <td class="bold">Payment Status:</td>
                <td>@ViewBag.PaymentStatus</td>
            </tr>
        </table>
        <hr />
        @using (Html.BeginForm())
        {
            <div>
                <input type="submit" value="Delete Gas Bill Payment" class="btn btn-warning" /> ::
                <a class="btn btn-warning" href="/Payments/Index">Bills Payments</a>
            </div>
        }
    </div>
  21. In the Solution Explorer, under Views and under Home, double-click Index.cshtml
  22. To execute, on the main menu, click Debug -> Start Without Debugging
  23. Click the Gas Meters link

    Introduction to Maintenance of Data Sets

  24. Click the Delete link of the last record:

    Data Sets Maintenance - New Gas Meters

  25. Click the Remove this Gas Meter button

    Introduction to Maintenance of Data Sets

  26. Close the browser and return to your programming environment

Deleting a Record by its Index

When calling the DataRowCollection.Remove() method, you must pass an exact identification of the record. If you don't have that identification, you can delete a record based on its index. To do this, you would call the DataRowCollection.RemoveAt() method. Its syntax is:

public void RemoveAt(int index);

This method takes as argument the index of the record you want to delete. If a record with that index exists, it would be deleted.

Deleting all Records From a Table

To delete all records of a table, call the DataRowCollection.Clear() method. Its syntax is:

public void Clear();

This method is used to clear the table of all records. Here is an example:

@{
    tblStudent.Rows.Clear();
}

Deleting all Records From all Tables

If you have many tables in a data set and you want to delete all records in all tables, to assist you, the DataSet class is equipped with a method named Clear. Its syntax is:

public void Clear();

Here is an example:

using System.IO;
using System.Data;
using System.Web.Mvc;

namespace GasUtilityCompany.Controllers
{
    public class BusinessController : Controller
    {
        . . . No Change

        // GET: Business
        public ActionResult Index()
        {
            return View();
        }

        // GET: Business/CreateGasMeter
        public ActionResult CreateGasMeter(string MeterNumber, string Make, string Model, string CounterValue)
        {
            . . . No Change

            return View();
        }

        // GET: Services/CreateCustomerAccount
        public ActionResult CreateCustomerAccount()
        {
            return View();
        }

        // GET: Services/SaveCustomerAccount
        public ActionResult SaveCustomerAccount(string AccountNumber, string MeterNumber,
                                                string FirstName, string LastName,
                                                string Address, string City, string County, string State, string ZIPCode)
        {
            bool validNumber = false;
            bool validAccount = false;
            string fileGasCompany = Server.MapPath("~/App_Data/GasCompany.xml");

            if (!string.IsNullOrEmpty(AccountNumber))
            {
                validAccount = true;
            }

            if (System.IO.File.Exists(fileGasCompany))
            {
                using (FileStream fsGasMeters = new FileStream(fileGasCompany, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    dsServices.ReadXml(fsGasMeters);

                    for (int i = 0; i < dsServices.Tables[0].Rows.Count; i++)
                    {
                        DataRow drGasMeter = dsServices.Tables[0].Rows[i];

                        if (drGasMeter[0].ToString() == MeterNumber)
                        {
                            validNumber = true;
                            break;
                        }
                    }
                }
            }

            dsServices.Clear();
            
            if ((validAccount == true) && (validNumber == true))
            {
                if (System.IO.File.Exists(fileGasCompany))
                {
                    using (FileStream fsGasCompany = new FileStream(fileGasCompany, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        dsServices.ReadXml(fsGasCompany);
                    }
                }

                DataRow drCustomer = dtCustomers.NewRow();

                drCustomer["account-number"] = AccountNumber;
                drCustomer["meter-number"] = MeterNumber;
                drCustomer["first-name"] = FirstName;
                drCustomer["last-name"] = LastName;
                drCustomer["address"] = Address;
                drCustomer["city"] = City;
                drCustomer["county"] = County;
                drCustomer["state"] = State;
                drCustomer["zip-code"] = ZIPCode;

                dtCustomers.Rows.Add(drCustomer);

                using (FileStream fsGasCompany = new FileStream(fileGasCompany, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                {
                    dsServices.WriteXml(fsGasCompany);
                }
            }

            return RedirectToAction("CreateCustomerAccount");
        }
    }
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next