The Records of a Table
In our description of tables, we saw that a table was made of one or various columns that represented some categories of data. Here is an example of a…
| The Rows of a Table Introduction to Records | |
|---|---|
| The Rows of a Table | |
| Introduction to Records |
As previously discussed, a table consists of columns that represent distinct data categories, such as Title, Director, or Rating. Once the structure is defined, users can populate the table with specific values, a process known as data entry. Practical Learning: Working with Data Sets.
- Start Microsoft Visual C# and create a new Windows Forms Application named CollegeParkAutoParts2
- To create an icon, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> New Item...
- In the Templates list, click Icon File
- Set the Name to cpap1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- On the main menu, click File -> Save cpap1.ico As
- Select the bin\Debug folder of the current folder and click Save
- On the main menu, click File -> Close
- In the Solution Explorer, expand bin and expand Debug
- In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to cpap2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to year1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to year2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to make1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to make2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to model1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to model2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to category1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to category2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right-click Form1.cs and click Rename
- Type Central.cs and press Enter twice to display the Central form
- From the Components section of the Toolbox, click ImageList and click the form
- In the Properties window, click (Name) and type imgAutoParts
- Click the ellipsis button of the Images field
- In the Image Collection Editor, click Add
- Locate the folder that contains the icons you created and display it in the Look In combo box
- Select cpap1.ico and click Open
- In the same way, add the other pictures in the following order: cpap2.ico, year1.ico, year2.ico, make1.ico, make2.ico, model1.ico, model2.ico, category1.ico, and category1.ico
- Click OK
- Design the form as follows: Control Text Name Other Properties Label College Park Auto-Parts Font: Times New Roman, 20.25pt, style=Bold ForeColor: Blue Panel Height: 2 GroupBox Part Identification TreeView tvwAutoParts ImageList: imgAutoParts GroupBox Available Parts ListView lvwAutoParts FullRowSelect: True GridLines: True View: Details Columns (Name) Text TextAlign Width colPartNumber Part # colPartName Part Name 300 colUnitPrice Unit Price Right 80 GroupBox Customer Order - Selected Parts Label Part # Label Part Name Label Unit Price Label Qty Label Sub Total TextBox txtPartNumber TextBox txtPartName TextBox 0.00 txtUnitPrice TextAlign: Right TextBox 0 txtQuantity TextAlign: Right TextBox 0.00 txtSubTotal TextAlign: Right Button Add/Select btnAdd ListView lvwSelectedParts FullRowSelect: True GridLines: True View: Details Columns (Name) Text TextAlign Width colPartNumberSelected Part # 45 colPartNameSelected Part Name 274 colUnitPriceSelected Unit Price Right 58 colQuantitySelected Qty Right 28 colSubTotalSelected Sub-Total Right 58 GroupBox Order Summary Button New Au&to Part... btnNewAutoPart Label Receipt #: TextBox txtSave Button Save btnSave Label Tax Rate: TextBox 7.75 txtTaxRate TextAlign: Right Label % Label Parts Total: TextBox 0.00 txtPartsTotal TextAlign: Right Button &New Customer Order btnNewCustomerOrder Label Receipt #: TextBox txtOpen Button Save btnOpen Label Tax Amount: TextBox 0.00 txtTaxAmount TextAlign: Right Label Order Total: TextBox 0.00 txtOrderTotal TextAlign: Right Button Close btnClose
- Click the Available Parts list view
- In the Properties window, click the Events button and, in the Events section, double-click DoubleClick
- Implement the event as follows: private void lvwAutoParts_DoubleClick(object sender, EventArgs e) { ListViewItem lviAutoPart = lvwAutoParts.SelectedItems[0]; if( (lvwAutoParts.SelectedItems.Count == 0) || (lvwAutoParts.SelectedItems.Count > 1) ) return; txtPartNumber.Text = lviAutoPart.Text; txtPartName.Text = lviAutoPart.SubItems[1].Text; txtUnitPrice.Text = lviAutoPart.SubItems[2].Text; txtQuantity.Text = "1"; txtSubTotal.Text = lviAutoPart.SubItems[2].Text; txtQuantity.Focus(); }
- Return to the Central form
- Click the Unit Price text box and, in the Events section of the Properties window, double-click Leave
- Implement the event as follows: private void txtUnitPrice_Leave(object sender, EventArgs e) { double UnitPrice = 0.00D; int Quantity = 0; double SubTotal = 0.00D; try { UnitPrice = double.Parse(txtUnitPrice.Text); } catch (FormatException) { MessageBox.Show("Invalid Unit Price!"); } try { Quantity = int.Parse(txtQuantity.Text); } catch (FormatException) { MessageBox.Show("Invalid Quandtity!"); } SubTotal = UnitPrice * Quantity; txtSubTotal.Text = SubTotal.ToString("F"); } internal void CalculateOrder() { // Calculate the current total order and update the order double PartsTotal = 0.00; double TaxRate = 0.00; double TaxAmount = 0.00; double OrderTotal = 0.00; ListViewItem lviSelectedPart = lvwSelectedParts.Items[0]; foreach (ListViewItem lvi in lvwSelectedParts.Items) { ListViewItem.ListViewSubItem SubItem = lvi.SubItems[4]; PartsTotal += double.Parse(SubItem.Text); } try { TaxRate = double.Parse(txtTaxRate.Text) / 100; } catch (FormatException) { MessageBox.Show("Invalid Tax Rate"); } TaxAmount = PartsTotal * TaxRate; OrderTotal = PartsTotal + TaxAmount; txtOrderTotal.Text = PartsTotal.ToString("F"); txtTaxAmount.Text = TaxAmount.ToString("F"); txtOrderTotal.Text = OrderTotal.ToString("F"); }
- Return to the Central form and click the Qty text box
- In the Events section of the Properties, click Leave, then click the arrow of its combo box and select txtUnitPrice_Leave
- On the Central form, click the Selected Part list view (the list view in the bottom-right section of the form)
- In the Events section of the Properties window, double-click DoubleClick
- Implement the event as follows: private void lvwSelectedParts_DoubleClick(object sender, EventArgs e) { ListViewItem lviSelectedPart = lvwSelectedParts.SelectedItems[0]; if( (lvwSelectedParts.SelectedItems.Count == 0) || (lvwSelectedParts.SelectedItems.Count > 1) ) return; txtPartNumber.Text = lviSelectedPart.Text; txtPartName.Text = lviSelectedPart.SubItems[1].Text; txtUnitPrice.Text = lviSelectedPart.SubItems[2].Text; txtQuantity.Text = lviSelectedPart.SubItems[3].Text; txtSubTotal.Text = lviSelectedPart.SubItems[4].Text; lvwSelectedParts.Items.Remove(lviSelectedPart); CalculateOrder(); }
- Save all
A Data Source and a Data Member for the Data Grid View#
When creating an application, to deliver it to the user and make it ready for data entry, you can create one or more forms as we did in previous lessons. When it comes to a data set, the .NET Framework provides a control named data grid view. As opposed to a list view, instead of visually creating the columns and/or the items, you can specify the source of the records. This would equip the data grid view with the necessary columns and the records in the data set. After creating a data grid view, you can assign it a data source, such as a DataSet object. At design time, to specify the data source of a data grid view, in the Properties window, select the object in the DataSource field. At run time, to specify a data source, assign the appropriate object to the DataSource property. Here is an example:
public class Exercise : Form
{
DataGridView dgvStudents;
DataSet dsRedOakHighSchool;
DataTable tblRegistration;
DataColumn colFirstName;
DataColumn colLastName;
DataColumn colGender;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students Records";
dgvStudents = new DataGridView();
dgvStudents.Location = new Point(12, 12);
Controls.Add(dgvStudents);
colFirstName = new DataColumn("First Name");
colLastName = new DataColumn("Last Name");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student Registration");
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("Red Oak High School");
dsRedOakHighSchool.Tables.Add(tblRegistration);
dgvStudents.DataSource = dsRedOakHighSchool;
}
}To find out what the data source of a data grid view is, get the value of its DataSource property. After assigning a data source, you should assign a data member to the data grid view. To visually specify the data members, in the Properties window of the data grid view, after setting the data source, access the DataMember field and click its arrowed button. Then, in the list, select an object, such as a table of a data set. To programmatically specify the data member, after assigning the appropriate variable to the DataSource property, assign the name of the list, such as the object name of a table, to the DataMember property of the DataGridView object. Here is an example:
void InitializeComponent()
{
Text = "Students Records";
dgvStudents = new DataGridView();
dgvStudents.Location = new Point(12, 12);
Controls.Add(dgvStudents);
colFirstName = new DataColumn("First Name");
colLastName = new DataColumn("Last Name");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student Registration");
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("Red Oak High School");
dsRedOakHighSchool.Tables.Add(tblRegistration);
dgvStudents.DataSource = dsRedOakHighSchool;
dgvStudents.DataMember = "Student Registration";
}When you build an application for the user and want it ready for data entry, you can create one or more forms, as we did in earlier lessons. For a data set, the .NET Framework offers a control called data grid view. Unlike a list view, where the columns and items are created visually, you can instead point it to the record source. Doing so gives the data grid view the needed columns and the records from the data set. After you create a data grid view, you can assign a data source such as a DataSet object. At design time, choose the object in the DataSource field in the Properties window to set the data source. At run time, assign the appropriate object to the DataSource property. Here is an example:
Practical Learning: Introducing Data Records
- To create a dialog box, on the main menu, click Project -> Add Windows Form...
- Set the name to ItemsCategories and click Add
- From the Data section of the Toolbox, click DataSet and click the form
- On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: Categories (Name): dsCategories
- Click the Tables field and click its ellipsis button
- In the Tables Collection Editor, click Add
- In the Properties list, change the characteristics of the table as follows: TableName: Category (Name): tblCategory
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: CategoryName (Name): colCategoryName
- Click Close and click Close
- Design the form as follows: Control Text Name Additional Properties DataGridView dgvStudents Anchor: Top, Bottom, Left, Right DataSource: dsCategories DataMember: Category Button Close btnClose Anchor: Bottom, Right
- To create a dialog box, on the main menu, click Project -> Add Windows Form...
- Set the name to CarMakes and click Add
- From the Data section of the Toolbox, click DataSet and click the form
- On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: Makes (Name): dsMakes
- Click the Tables field and click its ellipsis button
- In the Tables Collection Editor, click Add
- In the Properties list, change the characteristics of the table as follows: TableName: Make (Name): tblMake
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: MakeName (Name): colMakeName
- Click Close and click Close
- Design the form as follows: Control Text Name Additional Properties DataGridView dgvStudents Anchor: Top, Bottom, Left, Right DataSource: dsMakes DataMember: Makes Button Close btnClose Anchor: Bottom, Right
- To create a dialog box, on the main menu, click Project -> Add Windows Form...
- Set the name to CarModels and click Add
- Display the list of makes form
- Right-click dsMakes and click Copy
- Display the list of models form
- Right-click its body and click Paste
- From the Data section of the Toolbox, click DataSet and click the form
- On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: Models (Name): dsModels
- Click the Tables field and click its ellipsis button
- In the Tables Collection Editor, click Add
- In the Properties list, change the characteristics of the table as follows: TableName: Car (Name): tblCar
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: Make (Name): colMake
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: Model (Name): colModel
- Click Close and click Close
- From the Data section of the Toolbox, click DataGridView and click the form
- In the Properties window, change its characteristics as follows: DataSource: dsModels DataMember: Models
- Under the Properties window, click Edit Columns... and change the columns as follows: Selected Columns: HeaderText DataPropertyName ColumnType DataSource DisplayMember Make Make Make DataGridViewComboBoxColumn dsMakes Make.MakeName Model Model Model
- Click OK
- Design the form as follows: Control Text Name Additional Properties DataGridView dgvStudents Anchor: Top, Bottom, Left, Right Button Close btnClose Anchor: Bottom, Right
- To create a new form, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> Windows Form...
- Set the Name to AutoParts and click Add
- Display the list of models form
- Click dsMakes
- Press and hold Shift
- Click dsModels
- Release Shift
- Press Ctrl + C
- Display the auto parts form
- Right-click its body and click Paste
- Display the list of categories form
- Right-click dsCategories and click Copy
- Display the auto parts form
- Right-click its body and click Paste
- From the Data section of the Toolbox, click DataSet and click the form
- In the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: StoreItems (Name): dsStoreItems
- Click Tables and click its ellipsis button
- In the Properties list, change the characteristics of the table as follows: TableName: StoreItem (Name): tblStoreItem
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add continuously and create the columns as follows: ColumnName (Name) PartNumber colPartNumber Year colYear Make colMake Model colModel Category colCategory PartName colPartName UnitPrice colUnitPrice
- Click Close and click Close
- From the Data section of the Toolbox, click DataGridView and click the form
- In the Properties window, change its characteristics as follows: DataSource: dsStoreItems DataMember: StoreItems
- Under the Properties window, click Edit Columns... and change the columns as follows: Selected Columns: HeaderText Data Property Name ColumnType DataSource DisplayMember Width Part # Part # PartNumber 50 Year Year Year 40 Make Make Make DataGridView ComboBoxColumn dsMakes Make.MakeName 85 Model Model Model DataGridView ComboBoxColumn dsModels CarModel.Model 130 Category Category Category DataGridView ComboBoxColumn dsCategories Category.CategoryName 120 Part Name Part Name PartName 185 Unit Price Unit Price UnitPrice 65
- Click OK
- Design the form as follows: Control Text Name Other Properties DataGridView dgvStoreItems DataSource: dsStoreItems DataMember: AutoPart Anchor: Top, Bottom, Left, Right Button New Make... btnNewMake Anchor: Bottom, Left Button New Model... btnNewModel Anchor: Bottom, Left Button New Category... btnNewCategory Anchor: Bottom, Left Button Close btnClose Anchor: Bottom, Right
- Double-click the New Make button and implement the event as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace CollegeParkAutoParts2 { public partial class AutoParts : Form { public AutoParts() { InitializeComponent(); } private void btnNewMake_Click(object sender, EventArgs e) { CarMakes frmMakes = new CarMakes(); frmMakes.ShowDialog(); } } }
- Return to the Part Editor dialog box and double-click the New Model button
- Implement the event as follows: private void btnNewModel_Click(object sender, EventArgs e) { CarModels frmModels = new CarModels(); frmModels.ShowDialog(); }
- Return to the Part Editor dialog box and double-click the New Category button
- Implement the event as follows: private void btnNewCategory_Click(object sender, EventArgs e) { ItemsCategories frmCategories = new ItemsCategories(); frmCategories.ShowDialog(); }
- Display the Central form and double-click the New Auto Part button
- Implement its event as follows: internal void ShowAutoParts() { } private void btnNewAutoPart_Click(object sender, EventArgs e) { AutoParts frmParts = new AutoParts(); if (frmParts.ShowDialog() == DialogResult.Cancel) ShowAutoParts(); }
- Execute the application to make sure everything is working fine
- Close the form(s) and return to your programming environment
The Rows of a Table#
A record on a table is represented as a row (horizontal) of data. A row, or record, is an object based on the DataRow class. To support the various records that belong to a table, the DataTable class is equipped with a property called Rows. The DataTable.Rows property is an object of the DataRowCollection class. The DataRowCollection class provides the necessary properties and methods you can use to create and manage the records of a table. A record on a table is an object of type DataRow.
Creating a New Row#
When performing data entry and while doing it on a record, the record has a status that can be identified by the DataRow.RowState property which is a value based on the DataRowState enumeration. Before adding a new record to a table, you must let the table know. This is done by calling the DataTable.NewRow() method. Its syntax is:
public DataRow NewRow();The DataTable.NewRow() method returns a DataRow object. Here is an example of calling it:
void InitializeComponent()
{
DataRow rowStudent = tblRegistration.NewRow();
}Data Entry#
Introduction#
When you call the DataTable.NewRow() method, the record's status is DataRowState.Detached. After calling the DataTable.NewRow() method, you can specify the value that the column would carry. To do this, you must specify the table's column whose value you want to provide. You can locate a column based on an index as we mentioned already that the columns of a table are stored in the DataTable.Columns property which is based on the DataColumnCollection class. An example would be rowStudent["First Name"], which specifies the column named First Name. After specifying the column, assign it the desired but appropriate value. Here are examples of assigning values to the columns of a table:
void InitializeComponent()
{
DataRow rowStudent = tblRegistration.NewRow();
rowStudent["First Name"] = "Pauline";
rowStudent["Last Name"] = "Simms";
rowStudent["Gender"] = "Female";
}Each column can also be identified by its index in the table.
Adding a Record to a Table#
After specifying the value(s) of the column(s), you must add it (them) to the table. To do this, you must call the Add() method of the DataRowCollection class. This method is overloaded with two versions. One of the versions uses the following syntax:
public void Add(DataRow row);This method expects the name of the record as argument, which would be the value returned by a previous call to the DataTable.NewRow() method. Here is an example:
public class Exercise : Form
{
DataGridView dgvStudents;
DataSet dsRedOakHighSchool;
DataTable tblRegistration;
DataColumn colFirstName;
DataColumn colLastName;
DataColumn colGender;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students Records";
dgvStudents = new DataGridView();
dgvStudents.Location = new Point(12, 12);
Controls.Add(dgvStudents);
colFirstName = new DataColumn("First Name");
colLastName = new DataColumn("Last Name");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student Registration");
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("Red Oak High School");
dsRedOakHighSchool.Tables.Add(tblRegistration);
DataRow rowStudent = tblRegistration.NewRow();
rowStudent["First Name"] = "Pauline";
rowStudent["Last Name"] = "Simms";
rowStudent["Gender"] = "Female";
tblRegistration.Rows.Add(rowStudent);
dgvStudents.DataSource = dsRedOakHighSchool;
dgvStudents.DataMember = "Student Registration";
}
}This would produce:
When the record has been added to the table, the record has a status of DataRowState.Added.
Adding an Array of Records#
The above version of the DataRowCollection.Add() method means that you must identify each column before assigning a value to it. If you already know the sequence of columns and don't need to explicitly identify them, you can store all values in an array and simply add the array as a complete record. To support this, the DataRowCollection class provide another version of the .Add() method whose syntax is:
public virtual DataRow Add(object[] values);Here is an example:
void InitializeComponent()
{
. . . No Change
DataRow rowStudent = tblRegistration.NewRow();
rowStudent["First Name"] = "Pauline";
rowStudent["Last Name"] = "Simms";
rowStudent["Gender"] = "Female";
tblRegistration.Rows.Add(rowStudent);
object[] arrRecord = { "Edward", "Zaks", "Male" };
tblRegistration.Rows.Add(arrRecord);
dgvStudents.DataSource = dsRedOakHighSchool;
dgvStudents.DataMember = "Student Registration";
}This would produce:
There is an alternative to this second version of the DataRowCollection.Add() method. As opposed to passing an array of values to the Add() method, you can first define an array, assign that array to a DataRow variable, then pass that DataRow object to the Add() method. To support this technique, the DataRow class is equipped with an ItemArray property that expects an array. Here is an example
void InitializeComponent()
{
Text = "Students Records";
dgvStudents = new DataGridView();
dgvStudents.Location = new Point(12, 12);
Controls.Add(dgvStudents);
colFirstName = new DataColumn("First Name");
colLastName = new DataColumn("Last Name");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student Registration");
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("Red Oak High School");
dsRedOakHighSchool.Tables.Add(tblRegistration);
DataRow rowStudent = tblRegistration.NewRow();
rowStudent["First Name"] = "Pauline";
rowStudent["Last Name"] = "Simms";
rowStudent["Gender"] = "Female";
tblRegistration.Rows.Add(rowStudent);
object[] arrRecord = { "Edward", "Zaks", "Male" };
tblRegistration.Rows.Add(arrRecord);
object[] arrStudent = { "Geraldine", "Rodetsky", "Unknown" };
rowStudent = tblRegistration.NewRow();
rowStudent.ItemArray = arrStudent;
tblRegistration.Rows.Add(rowStudent);
dgvStudents.DataSource = dsRedOakHighSchool;
dgvStudents.DataMember = "Student Registration";
}This would produce:
After creating the records of a table, if a record contains invalid values, the DataRow.HasErrors property can help you identify them.
The Number of Records of a Table#
After you have created a table and its columns but before adding any row, the number of the table's records is set to 0. Every time you add a new record, the number of records is incremented by 1. To get the number of records that a table contains, access the Count property of its DataRowCollection collection.
Saving the Records of a Table#
Introduction#
When the application closes, unfortunately, all the information created while the application was running is lost. While the first goal of an application is to create one or more lists used to organize information, probably the essence of an information-based or a data-based application is to preserve information created when using the application and be able to retrieve that information the next time the application runs, without re-creating it. Of course, there are various ways you can save the information created in an application. As the DataSet class is equipped with all the necessary features used to create and manage one or more lists of an application, it also provides a very high level of saving the information stored in its lists.
Saving a Data Set#
Once a new record has been created or when the lists of the data set have been populated with information, you can save the changes and store them to a computer file. By default, the DataSet class is equipped to save its lists as XML. To support this, it is equipped with the WriteXml() method that is overloaded with various versions. One of the versions of this method uses the following syntax:
public void WriteXml(string fileName);This method takes as argument the name of the new file or its path. When providing this argument, make sure you add the .xml extension to the file name. This method does two things: it checks the existence of the file and it saves it. If the file you provided is not found in the path, this method creates it and writes the record(s) to it. If the file exists already, this method opens it, finds its end, and appends the new data at the end. This makes the method very useful and friendly. Here is an example of saving a data set using this method:
void InitializeComponent()
{
. . . No Change
tblRegistration.Rows.Add(rowStudent);
dsRedOakHighSchool.WriteXml("students.xml");
}If you want to control whether the file should be created from scratch, instead of passing the name of the file to this method, first create a stream using a Stream-derived class such as FileStream. This allows specifying the necessary options using the FileMode, FileAccess, and FileShare properties. Once the stream is ready, pass it to the WriteXml() method because it is also overloaded with the following syntax:
public void WriteXml(Stream stream);Here is an example:
using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
public class Exercise : Form
{
DataGridView dgvStudents;
DataSet dsRedOakHighSchool;
DataTable tblRegistration;
DataColumn colFirstName;
DataColumn colLastName;
DataColumn colGender;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students Records";
dgvStudents = new DataGridView();
dgvStudents.Location = new Point(12, 12);
Controls.Add(dgvStudents);
colFirstName = new DataColumn("First Name");
colLastName = new DataColumn("Last Name");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student Registration");
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("Red Oak High School");
dsRedOakHighSchool.Tables.Add(tblRegistration);
DataRow rowStudent = tblRegistration.NewRow();
rowStudent["First Name"] = "Pauline";
rowStudent["Last Name"] = "Simms";
rowStudent["Gender"] = "Female";
tblRegistration.Rows.Add(rowStudent);
object[] arrRecord = { "Edward", "Zaks", "Male" };
tblRegistration.Rows.Add(arrRecord);
object[] arrStudent = { "Geraldine", "Rodetsky", "Unknown" };
rowStudent = tblRegistration.NewRow();
rowStudent.ItemArray = arrStudent;
tblRegistration.Rows.Add(rowStudent);
FileStream stmStudents = new FileStream("registration.xml",
FileMode.Create,
FileAccess.Write);
dsRedOakHighSchool.WriteXml(stmStudents);
}
}
public class Program
{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}If you want the file to be formatted as text, you can use the following version of the method:
public void WriteXml(TextWriter writer);If you prefer to use an XmlWriter variable to manage the file, use the following version of the method:
public void WriteXml(XmlWriter writer);Obviously to use this method, you must first define an XmlWriter type of variable. Practical Learning: Saving the Records of a Data Set
- Display the ItemsCategories form and double-click the Close button
- Implement the event as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CollegeParkAutoParts2 { public partial class ItemsCategories : Form { public ListOfCategories() { InitializeComponent(); } private void btnClose_Click(object sender, EventArgs e) { string strDirectory = @"C:\College Park Auto Parts"; // If this directory doesn't exist, create it Directory.CreateDirectory(strDirectory); dsCategories.WriteXml(strDirectory + "\\categories.xml"); Close(); } } }
- Display the CarMakes form and double-click the Close button
- Implement the event as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CollegeParkAutoParts2 { public partial class CarMakes : Form { public ListOfMakes() { InitializeComponent(); } private void btnClose_Click(object sender, EventArgs e) { string strDirectory = @"C:\College Park Auto Parts"; // If this directory doesn't exist, create it Directory.CreateDirectory(strDirectory); dsMakes.WriteXml(strDirectory + "\\makes.xml"); Close(); } } }
- Display the Models form and double-click the Close button
- Implement the event as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CollegeParkAutoParts2 { public partial class CarModels : Form { public ListOfModels() { InitializeComponent(); } private void btnClose_Click(object sender, EventArgs e) { string strDirectory = @"C:\College Park Auto Parts"; // If this directory doesn't exist, create it Directory.CreateDirectory(strDirectory); dsModels.WriteXml(strDirectory + "\\models.xml"); Close(); } } }
- Display the Auto Parts form and double-click the Close button
- Implement its event as follows: private void btnClose_Click(object sender, EventArgs e) { string strDirectory = @"C:\College Park Auto Parts"; // If this directory doesn't exist, create it Directory.CreateDirectory(strDirectory); dsStoreItems.WriteXml(strDirectory + "\\StoreItems.xml"); Close(); }
- Save all
Opening a Data Set#
To open the data saved from a list, the DataSet class provides the ReadXml() method that is overloaded with various versions. One of the versions of this method uses the following syntax:
public XmlReadMode ReadXml(string fileName);This method requires either the name or the full path of an existing XML file. It opens the file and applies the XML formatting used when the data was originally saved. Here is how you call it:
using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
public class Exercise : Form
{
DataGridView dgvStudents;
DataSet dsRedOakHighSchool;
DataTable tblRegistration;
DataColumn colFirstName;
DataColumn colLastName;
DataColumn colGender;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students Records";
dgvStudents = new DataGridView();
dgvStudents.Location = new Point(12, 12);
Controls.Add(dgvStudents);
colFirstName = new DataColumn("First Name");
colLastName = new DataColumn("Last Name");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student Registration");
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("Red Oak High School");
dsRedOakHighSchool.Tables.Add(tblRegistration);
if( File.Exists("students.xml") )
{
dsRedOakHighSchool.ReadXml("students.xml");
dgvStudents.DataSource = dsRedOakHighSchool;
dgvStudents.DataMember = "Student Registration";
}
}
}
public class Program
{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}Although this method can read any XML file, if you use it to open a file that was saved by someone else or another application and you want to use it in your application, you should be familiar with the names of its nodes. If it contains names that are not "registered" or recognized by your DataSet object, the lists that compose your application may not be able to read it, not because the list was not formatted right, but because the lists of your application would be holding different names. If the file was saved using a Stream-based class, you can pass a stream to the method based on the following syntax:
public XmlReadMode ReadXml(Stream stream);In the same way, the method provides an equivalent version for the TextWriter and the XmlWriter versions:
public XmlReadMode ReadXml(TextReader reader);
public XmlReadMode ReadXml(XmlReader reader);To use one of these versions, you must first define a TextWriter or an XmlReader type of variable. When retrieving the content of the XML file, if you want it delivered as text, call the DataSet.GetXml() method. Its syntax is:
public string GetXml();As you can see, this method returns a string. Once a file has been opened, you can explore its content. The most obvious operation related to opening a data set consists of viewing its records. Practical Learning: Opening the Records for a Data Set
- Display the ItemsCategories form and double-click an unoccupied area of its body
- Implement the event as follows: private void ItemsCategories_Load(object sender, EventArgs e) { string Filename = @"C:\College Park Auto Parts\categories.xml"; if (File.Exists(Filename)) dsCategories.ReadXml(Filename); }
- Display the CarMakes form and double-click an unoccupied area of its body
- Implement the event as follows: private void CarMakes_Load(object sender, EventArgs e) { string Filename = @"C:\College Park Auto Parts\makes.xml"; if (File.Exists(Filename)) dsMakes.ReadXml(Filename); }
- Display the CarModels form and double-click an unoccupied area of its body
- Implement the event as follows: private void CarModels_Load(object sender, EventArgs e) { string Filename = @"C:\College Park Auto Parts\makes.xml"; if (File.Exists(Filename)) dsMakes.ReadXml(Filename); Filename = @"C:\College Park Auto Parts\models.xml"; if (File.Exists(Filename)) dsModels.ReadXml(Filename); }
- Display the AutoParts form and double-click an unoccupied area of its body
- Implement the event as follows: private void AutoParts_Load(object sender, EventArgs e) { string Filename = @"C:\College Park Auto Parts\StoreItems.xml"; if( File.Exists(Filename) ) dsStoreItems.ReadXml(Filename); }
- Return to the form and, in the Properties window, click the Events button
- In the Events section of the Properties window, double-click Activated and implement the event as follows: private void AutoParts_Activated(object sender, EventArgs e) { string Filename = @"C:\College Park Auto Parts\makes.xml"; if (File.Exists(Filename)) dsMakes.ReadXml(Filename); Filename = @"C:\College Park Auto Parts\models.xml"; if (File.Exists(Filename)) dsModels.ReadXml(Filename); Filename = @"C:\College Park Auto Parts\categories.xml"; if (File.Exists(Filename)) dsCategories.ReadXml(Filename); }
- Execute the application
- Click the New Auto Part button and click the New Make button
- Create a few makes as follows: Ford Dodge Toyota Honda
- Click the New Model button and create a few models as follows: Ford Escort SE L4 2.0 Dodge Caravan SE L4 2.4 Toyota Rav4 2WD/4-Door Honda Civic 1.7 EX 4DR Ford Taurus LX V6 3.0 Honda Accord 2.3 LX 4DR
- Click the New Category button and create a few categories as follows: Exhaust Air Intake Fuel Injection Cooling System Engine Electrical
- Close the form(s) and return to your programming environment
Committing or Rejecting Changes to a List#
When a user has created a record, the data set that holds the information is considered to have been modified because, obviously, it does not have the same information or the same records it had when the application was launched. You, as the programmer, have the option of accepting the changes or rejecting them. To accept the changes, call the DataSet.AcceptChanges() method. Its syntax is:
public void AcceptChanges();If you don't want the changes to take effect, you can reject them by calling the DataSet.RejectChanges() method. Its syntax is:
public virtual void RejectChanges();This method can be called to dismiss whatever changes were made on the records of the list(s).
Locating Records and Their Values#
Locating a Record#
Consider the following data set:
using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
public class Exercise : Form
{
ListView lvwStudents;
DataSet dsRedOakHighSchool;
DataTable tblRegistration;
DataColumn colStudentNumber;
DataColumn colFirstName;
DataColumn colLastName;
DataColumn colGender;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students Records";
lvwStudents = new ListView();
lvwStudents.Location = new Point(12, 12);
Controls.Add(lvwStudents);
colStudentNumber = new DataColumn("StudentNumber");
colFirstName = new DataColumn("FirstName");
colLastName = new DataColumn("LastName");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student");
tblRegistration.Columns.Add(colStudentNumber);
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("SchoolRecords");
dsRedOakHighSchool.Tables.Add(tblRegistration);
object[] objStudents1 = { "920759", "Pauline", "Simms", "Female" };
tblRegistration.Rows.Add(objStudents1);
object[] objStudents2 = { "281174", "Geraldine", "Rodetsky", "Unknown" };
tblRegistration.Rows.Add(objStudents2);
object[] objStudents3 = { "400795", "Edward", "Zaks", "Male" };
tblRegistration.Rows.Add(objStudents3);
object[] objStudents4 = { "931579", "Jeannete", "Palau", "Female" };
tblRegistration.Rows.Add(objStudents4);
object[] objStudents5 = { "315825", "Kate", "Hooks", "Unknown" };
tblRegistration.Rows.Add(objStudents5);
dsRedOakHighSchool.WriteXml("students.xml");
}
}
public class Program
{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}This would produce:
<?xml version="1.0" standalone="yes"?>
<SchoolRecords>
<Student>
<StudentNumber>920759</StudentNumber>
<FirstName>Pauline</FirstName>
<LastName>Simms</LastName>
<Gender>Female</Gender>
</Student>
<Student>
<StudentNumber>281174</StudentNumber>
<FirstName>Geraldine</FirstName>
<LastName>Rodetsky</LastName>
<Gender>Unknown</Gender>
</Student>
<Student>
<StudentNumber>400795</StudentNumber>
<FirstName>Edward</FirstName>
<LastName>Zaks</LastName>
<Gender>Male</Gender>
</Student>
<Student>
<StudentNumber>931579</StudentNumber>
<FirstName>Jeannete</FirstName>
<LastName>Palau</LastName>
<Gender>Female</Gender>
</Student>
<Student>
<StudentNumber>315825</StudentNumber>
<FirstName>Kate</FirstName>
<LastName>Hooks</LastName>
<Gender>Unknown</Gender>
</Student>
</SchoolRecords>Before performing any operation on a record, you must be able to locate it. That is, you must be able to identify a record among the various records of a table. The records of a table are stored in a list based on the DataRowCollection class. To locate a record in the DataTable.Rows collection, the DataRowCollection class has an indexed property that is defined as follows:
public DataRow this[int index] {get;}The first record has an index of 0. The second record has an index of 1, and so on. Here is an example of identifying each column:
void InitializeComponent()
{
Text = "Students Records";
Size = new Size(320, 160);
lvwStudents = new ListView();
lvwStudents.Location = new Point(12, 12);
lvwStudents.Size = new Size(290, 110);
lvwStudents.View = View.Details;
lvwStudents.GridLines = true;
lvwStudents.FullRowSelect = true;
Controls.Add(lvwStudents);
colStudentNumber = new DataColumn("StudentNumber");
colFirstName = new DataColumn("FirstName");
colLastName = new DataColumn("LastName");
colGender = new DataColumn("Gender");
tblRegistration = new DataTable("Student");
tblRegistration.Columns.Add(colStudentNumber);
tblRegistration.Columns.Add(colFirstName);
tblRegistration.Columns.Add(colLastName);
tblRegistration.Columns.Add(colGender);
dsRedOakHighSchool = new DataSet("SchoolRecords");
dsRedOakHighSchool.Tables.Add(tblRegistration);
dsRedOakHighSchool.ReadXml("students.xml");
lvwStudents.Columns.Add("Student #");
lvwStudents.Columns.Add("First Name", 75);
lvwStudents.Columns.Add("Last Name", 75);
lvwStudents.Columns.Add("Gender");
for (int i = 0; i < tblRegistration.Rows.Count; i++)
{
DataRow rowStudent = tblRegistration.Rows[i];
}
}Each record of a table is an object of type DataRow. When you access a record, the compiler would check whether the record exists. If a record with that index exists, its DataRow value is produced.
Locating a Value by a Column's Index#
Once you have located a record, you can find a particular value you are interested in, and you have tremendous options. Here is an example where the user had located and clicked the value "Paulson" in a record:
Consider the following table of records:
To locate a value in a data set, you need two pieces of information: the record and the column. We have seen how to located a record. Each value of a table is created under a particular column. Therefore, you must be able to specify the column under which the value exists. To identify the columns of a table, the DataRow class is equipped with the overloaded indexed property which comes in 6 versions. As seen in previous lessons, the columns of a table are indexed with the first column at 0, the second at 1, and so on. To allow you to identify a column by its index, one of the versions of the DataRow's indexed property uses the following syntax:
public object this[int columnIndex] {get; set;}This property expects the index of the column. Here are examples:
void InitializeComponent()
{
. . . No Change
for (int i = 0; i < tblRegistration.Rows.Count; i++)
{
DataRow rowStudent = tblRegistration.Rows[i];
ListViewItem lviStudent =
new ListViewItem(rowStudent[0].ToString());
lviStudent.SubItems.Add(rowStudent[1].ToString());
lviStudent.SubItems.Add(rowStudent[2].ToString());
lviStudent.SubItems.Add(rowStudent[3].ToString());
lvwStudents.Items.Add(lviStudent);
}
}To access a record directly without first declaring a DataRow variable, the above code can also be written as follows:
void InitializeComponent()
{
. . . No Change
for (int i = 0; i < tblRegistration.Rows.Count; i++)
{
ListViewItem lviStudent =
new ListViewItem(tblRegistration.Rows[i][0].ToString());
lviStudent.SubItems.Add(tblRegistration.Rows[i][1].ToString());
lviStudent.SubItems.Add(tblRegistration.Rows[i][2].ToString());
lviStudent.SubItems.Add(tblRegistration.Rows[i][3].ToString());
lvwStudents.Items.Add(lviStudent);
}
}You can use a foreach loop to visit the members of a DataColumnCollection collection. Like the DataColumnCollection class, the DataRowCollection class implements the GetEnumerator() method of the IEnumerable interface. This means that you can use the foreach loop on a collection of records to visit each member. Here is an example:
void InitializeComponent()
{
. . . No Change
foreach(DataRow rowStudent in tblRegistration.Rows)
{
ListViewItem lviStudent =
new ListViewItem(rowStudent[0].ToString());
lviStudent.SubItems.Add(rowStudent[1].ToString());
lviStudent.SubItems.Add(rowStudent[2].ToString());
lviStudent.SubItems.Add(rowStudent[3].ToString());
lvwStudents.Items.Add(lviStudent);
}
}Locating a Value by the Column Object Name#
Instead of using the index of a column, you can locate a value using the object name of its column. To do this, you can use the following syntax of the DataRow indexed property:
public object this[string ColumnName] {get; set;}This property expects the object name of the column passed in its square brackets. Here are examples:
void InitializeComponent()
{
. . . No Change
for (int i = 0; i < tblRegistration.Rows.Count; i++)
{
DataRow rowStudent = tblRegistration.Rows[i];
ListViewItem lviStudent =
new ListViewItem(rowStudent["StudentNumber"].ToString());
lviStudent.SubItems.Add(rowStudent["FirstName"].ToString());
lviStudent.SubItems.Add(rowStudent["LastName"].ToString());
lviStudent.SubItems.Add(rowStudent["Gender"].ToString());
lvwStudents.Items.Add(lviStudent);
}
}Locating a Value by the Column Variable Name#
Instead of using the index or the object name of a column, you can also locate a value using the variable name of its column. To do this, you can use the following syntax of the DataRow indexed property:
public object this[DataColumn column] {get; set;}This property expects the object name of the column passed in its square brackets. Here are examples:
void InitializeComponent()
{
. . . No Change
for (int i = 0; i < tblRegistration.Rows.Count; i++)
{
DataRow rowStudent = tblRegistration.Rows[i];
ListViewItem lviStudent =
new ListViewItem(rowStudent[colStudentNumber].ToString());
lviStudent.SubItems.Add(rowStudent[colFirstName].ToString());
lviStudent.SubItems.Add(rowStudent[colLastName].ToString());
lviStudent.SubItems.Add(rowStudent[colGender].ToString());
lvwStudents.Items.Add(lviStudent);
}
}Locating a Value From the Column Collection#
As mentioned already, to access a record, you can pass its index to the indexed property of the DataRowCollection, which produces a DataRow object. Using these concepts, you can access the values of a table. Here is an example:
void InitializeComponent()
{
. . . No Change
foreach(DataRow rowStudent in tblRegistration.Rows)
{
foreach (DataColumn col in tblRegistration.Columns)
{
MessageBox.Show(rowStudent[col].ToString());
}
break;
}
}This code allows you to access a record using a row of a table and to locate a value based on the name of its column, but the above code does not allow you to clearly identify the column whose value you want to access. To clearly locate a value, you should name its column and to do this, you can pass the column name to the indexed property of the record. Here are examples:
void InitializeComponent()
{
. . . No Change
foreach (DataRow rowStudent in tblRegistration.Rows)
{
foreach (DataColumn col in tblRegistration.Columns)
{
ListViewItem lviStudent =
new ListViewItem(rowStudent["StudentNumber"].ToString());
lviStudent.SubItems.Add(rowStudent["FirstName"].ToString());
lviStudent.SubItems.Add(rowStudent["LastName"].ToString());
lviStudent.SubItems.Add(rowStudent["Gender"].ToString());
lvwStudents.Items.Add(lviStudent);
break;
}
}
}Whether using a for or foreach loop, if you attempt to access an index that is negative or exceeds the total number of records, the system will throw an IndexOutOfRangeException. Practical Learning: Accessing Data Set Values.
- In the Solution Explorer, Double-click Central.cs
- From the Data section of the Toolbox, click DataSet and click the form
- In the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: StoreItems (Name): dsStoreItems
- Click Tables and click its ellipsis button
- In the Properties list, change the characteristics of the table as follows: TableName: AutoPart (Name): tblAutoPart
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add continuously and create the columns as follows: ColumnName (Name) PartNumber colPartNumber Year colYear Make colMake Model colModel Category colCategory PartName colPartName UnitPrice colUnitPrice
- Click Close and click Close
- Right-click the form and click View Code
- Change the ShowAutoParts method as follows: internal void ShowAutoParts() { tvwAutoParts.Nodes.Clear(); TreeNode nodRoot = tvwAutoParts.Nodes.Add("College Park Auto-Parts", "College Park Auto-Parts", 0, 1); // Show the years nodes for (int years = DateTime.Today.Year + 1; years >= 1960; years--) nodRoot.Nodes.Add(years.ToString(), years.ToString(), 2, 3); tvwAutoParts.SelectedNode = nodRoot; // Expand the root node tvwAutoParts.ExpandAll(); // This is the file that holds the list of store items on sale string Filename = @"C:\College Park Auto Parts\StoreItems.xml"; if (File.Exists(Filename)) { dsStoreItems.ReadXml(Filename); // Add the makes to the years foreach (TreeNode nodYear in nodRoot.Nodes) { List<string> lstMakes = new List<string>(); foreach (DataRow row in tblAutoPart.Rows) { if (nodYear.Text == row["Year"].ToString()) { if (!lstMakes.Contains(row["Make"].ToString())) lstMakes.Add(row["Make"].ToString()); } } foreach (string strMake in lstMakes) nodYear.Nodes.Add(strMake, strMake, 4, 5); } // Add the models to the makes foreach (TreeNode nodYear in nodRoot.Nodes) { foreach (TreeNode nodMake in nodYear.Nodes) { List<string> lstModels = new List<string>(); foreach (DataRow row in tblAutoPart.Rows) { if ((nodYear.Text == row["Year"].ToString()) && (nodMake.Text == row["Make"].ToString())) { if (!lstModels.Contains(row["Model"].ToString())) lstModels.Add(row["Model"].ToString()); } } foreach (string strModel in lstModels) nodMake.Nodes.Add(strModel, strModel, 6, 7); } } // Show the categories nodes foreach (TreeNode nodYear in nodRoot.Nodes) { foreach (TreeNode nodMake in nodYear.Nodes) { foreach (TreeNode nodModel in nodMake.Nodes) { List<string> lstCategories = new List<string>(); foreach (DataRow row in tblAutoPart.Rows) { if ((nodYear.Text == row["Year"].ToString()) && (nodMake.Text == row["Make"].ToString()) && (nodModel.Text == row["Model"].ToString())) { if (!lstCategories.Contains(row["Category"].ToString())) lstCategories.Add(row["Category"].ToString()); } } foreach (string strCategory in lstCategories) nodModel.Nodes.Add(strCategory, strCategory, 8, 9); } } } } }
- Return to the form and double-click an unoccupied area of its body to generate its Load event
- Implement the event as follows: private void Central_Load(object sender, EventArgs e) { ShowAutoParts(); }
- Return to the Central form and click the Part # text box
- In the Events section of the Properties window, double-click Leave and implement the event as follows: private void txtPartNumber_Leave(object sender, EventArgs e) { foreach (DataRow row in tblAutoPart.Rows) { if (row["PartNumber"].ToString() == txtPartNumber.Text) { txtPartName.Text = row["PartName"].ToString(); txtUnitPrice.Text = row["UnitPrice"].ToString(); txtQuantity.Text = "0"; txtSubTotal.Text = "0.00"; } } }
- Return to the Central form and double-click the Add/Select button
- Implement the event as follows: private void btnAdd_Click(object sender, EventArgs e) { if (txtPartNumber.Text.Length == 0) { MessageBox.Show("There is no part to be added to the order"); return; } ListViewItem lviSelectedPart = new ListViewItem(txtPartNumber.Text); lviSelectedPart.SubItems.Add(txtPartName.Text); lviSelectedPart.SubItems.Add(txtUnitPrice.Text); lviSelectedPart.SubItems.Add(txtQuantity.Text); lviSelectedPart.SubItems.Add(txtSubTotal.Text); lvwSelectedParts.Items.Add(lviSelectedPart); CalculateOrder(); }
- Scroll up in the file and add the following namespaces: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; namespace CollegeParkAutoParts2
- Return to the Central form and double-click the New Customer Order button
- Implement the event as follows: private void btnNewCustomerOrder_Click(object sender, EventArgs e) { int ReceiptNumber = 0; string Filename = @"C:\College Park Auto Parts\receipts.xml"; XmlDocument DOMReceipts = new XmlDocument(); if (File.Exists(Filename)) { DOMReceipts.Load(Filename); XmlElement RootReceipts = DOMReceipts.DocumentElement; XmlNodeList ListOfReceiptNumbers = RootReceipts.GetElementsByTagName("ReceiptNumber"); ReceiptNumber = int.Parse(ListOfReceiptNumbers[ ListOfReceiptNumbers.Count - 1].InnerText); } txtSave.Text = (ReceiptNumber + 1).ToString(); txtTaxRate.Text = "5.75"; txtTaxAmount.Text = "0.00"; txtPartsTotal.Text = "0.00"; txtOrderTotal.Text = "0.00"; lvwSelectedParts.Items.Clear(); }
- Return to the Central form and click the tree view
- In the Properties window, click the Events button and, in the Events section, double-click NodeMouseClick
- Implement the event as follows: private void tvwAutoParts_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { TreeNode nodClicked = e.Node; if (nodClicked.Level == 4) lvwAutoParts.Items.Clear(); try { foreach (DataRow row in tblAutoPart.Rows) { if ((row["Category"].ToString() == nodClicked.Text) && (row["Model"].ToString() == nodClicked.Parent.Text) && (row["Make"].ToString() == nodClicked.Parent.Parent.Text) && (row["Year"].ToString() == nodClicked.Parent.Parent.Parent.Text)) { ListViewItem lviAutoPart = new ListViewItem(row["PartNumber"].ToString()); lviAutoPart.SubItems.Add(row["PartName"].ToString()); lviAutoPart.SubItems.Add(row["UnitPrice"].ToString()); lvwAutoParts.Items.Add(lviAutoPart); } } } catch (NullReferenceException) { } }
- Return to the Central form and double-click the Save button
- Implement its event as follows: private void btnSave_Click(object sender, EventArgs e) { // This is the file that holds the receipts string Filename = @"C:\College Park Auto Parts\receipts.xml"; // Get a reference to the root XmlDocument DOMReceipts = new XmlDocument(); // We will create a list of all the parts // that the customer wants to purchase string strParts = ""; foreach (ListViewItem lviPart in lvwSelectedParts.Items) { strParts = strParts + "<Part>"; strParts = strParts + "<PartNumber>" + lviPart.SubItems[0].Text + "</PartNumber>"; strParts = strParts + "<PartName>" + lviPart.SubItems[1].Text + "</PartName>"; strParts = strParts + "<UnitPrice>" + lviPart.SubItems[2].Text + "</UnitPrice>"; strParts = strParts + "<Quantity>" + lviPart.SubItems[3].Text + "</Quantity>"; strParts = strParts + "<SubTotal>" + lviPart.SubItems[4].Text + "</SubTotal>"; strParts = strParts + "</Part>"; } // If this is the first customer order, ... if (!File.Exists(Filename)) { // If this is the first receipt to be created, // set the receipt number to 1 // and create the structure of the document DOMReceipts.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<CustomersOrders>" + "<Receipt>" + "<ReceiptNumber>1</ReceiptNumber>" + strParts + "<PartsTotal>" + txtPartsTotal.Text + "</PartsTotal><TaxRate>" + txtTaxRate.Text + "</TaxRate><TaxAmount>" + txtTaxAmount.Text + "</TaxAmount><OrderTotal>" + txtOrderTotal.Text + "</OrderTotal></Receipt></CustomersOrders>"); // Save the XML file DOMReceipts.Save(Filename); // Reset the customer order txtSave.Text = "2"; txtOpen.Text = "1"; txtTaxRate.Text = "5.75"; txtTaxAmount.Text = "0.00"; txtPartsTotal.Text = "0.00"; txtOrderTotal.Text = "0.00"; lvwSelectedParts.Items.Clear(); } // If this is not the first customer order, ... else // if (File.Exists(Filename)) { XmlNode NodeCustomerOrder = null; // We will use a receipt number for each receipt int ReceiptNumber = int.Parse(txtSave.Text); // If at least one receipt had previously been created, // then open the XML file that holds the receipts // Store the XML file structure into the DOM DOMReceipts.Load(Filename); // Get a reference to the root element XmlElement RootCustomersOrders = DOMReceipts.DocumentElement; // Get a list of the receipt numbers XmlNodeList ListOfReceipts = RootCustomersOrders.GetElementsByTagName("Receipt"); // Check each receipt foreach (XmlNode NodeCurrentReceipt in ListOfReceipts) { // Look for a receipt that has the same number // as in the Save text box if (NodeCurrentReceipt["ReceiptNumber"].InnerText == txtSave.Text) { // If you find it, reserve it NodeCustomerOrder = NodeCurrentReceipt; break; } } // Locate the last receipt number ReceiptNumber = int.Parse(txtSave.Text); // Create an element named Receipt XmlElement ElementReceipt = DOMReceipts.CreateElement("Receipt"); string strReceipt = "<ReceiptNumber>" + ReceiptNumber.ToString() + "</ReceiptNumber>" + strParts + "<PartsTotal>" + txtPartsTotal.Text + "</PartsTotal><TaxRate>" + txtTaxRate.Text + "</TaxRate><TaxAmount>" + txtTaxAmount.Text + "</TaxAmount><OrderTotal>" + txtOrderTotal.Text + "</OrderTotal>"; // Create the XML code of the new element ElementReceipt.InnerXml = strReceipt; // If this is a new customer order if (NodeCustomerOrder == null) { // Add the new receipt to the file DOMReceipts.DocumentElement.AppendChild(ElementReceipt); } // If the customer order existed already, we will only update it else // if (NodeCustomerOrder != null) { // Replace the existing customer order with the current one DOMReceipts.DocumentElement.ReplaceChild(ElementReceipt, _ NodeCustomerOrder); } // Save the XML file DOMReceipts.Save(Filename); // Reset the customer order btnNewCustomerOrder_Click(sender, e); } }
- Return to the Central form and double-click the Open button
- Implement its event as follows: private void btnOpen_Click(object sender, EventArgs e) { XmlDocument DOMReceipts = new XmlDocument(); string Filename = @"C:\College Park Auto Parts\receipts.xml"; // Check that the file exists. If so, open it if (File.Exists(Filename)) { // This variable will allow us to know if we have the receipt number bool found = false; // Empty the list of selected parts lvwSelectedParts.Items.Clear(); // After opening the XML file, store it in the DOM DOMReceipts.Load(Filename); // Get a reference to the root element XmlElement RootReceipts = DOMReceipts.DocumentElement; // Get a list of the receipts in the file XmlNodeList ListOfReceipts = RootReceipts.GetElementsByTagName("Receipt"); // Check each receipt foreach (XmlNode nodReceipt in ListOfReceipts) { // Look for an receipt that has the same number // as on the Open text box if (nodReceipt["ReceiptNumber"].InnerText == txtOpen.Text) { // If you find it, make a note found = true; txtOpen.Text = nodReceipt["ReceiptNumber"].InnerText; txtSave.Text = nodReceipt["ReceiptNumber"].InnerText; // Retrieve the values of the receipt // and display them on the form try { foreach (XmlNode nodeReceipt in nodReceipt.ChildNodes) { XmlNode node = nodeReceipt.NextSibling.ChildNodes[0]; ListViewItem lviReceipt = new ListViewItem(node.InnerText); lviReceipt.SubItems.Add(node.NextSibling.InnerText); lviReceipt.SubItems.Add( node.NextSibling.NextSibling.InnerText); lviReceipt.SubItems.Add( node.NextSibling.NextSibling.NextSibling.InnerText); lviReceipt.SubItems.Add( node.NextSibling.NextSibling.NextSibling.NextSibling.InnerText); lvwSelectedParts.Items.Add(lviReceipt); } txtPartsTotal.Text = nodReceipt["PartsTotal"].InnerText; txtTaxRate.Text = nodReceipt["TaxRate"].InnerText; txtTaxAmount.Text = nodReceipt["TaxAmount"].InnerText; txtOrderTotal.Text = nodReceipt["OrderTotal"].InnerText; } catch (NullReferenceException) { } } } // If the receipt was not found, let the user know if (found == false) { MessageBox.Show("There is no customer order with that receipt number"); txtSave.Text = txtOpen.Text; } }// IF the XML file was not found, let the user know else MessageBox.Show("The file " + Filename + " was not found"); }
- Locate the Load event and change it as follows: private void Central_Load(object sender, EventArgs e) { ShowAutoParts(); btnNewCustomerOrder_Click(sender, e); }
- Return to the Central form and double-click the Close button
- Implement the event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
- Execute the application
- Click the New Auto Part button and use the Part Editor to create a few parts
- Close the Part Editor
- Create a few customer part orders and save them:
- Close the forms and return to your programming environment
- Execute the application again and open a previously saved order
- Close the forms and return to your programming environment
Exercises#
College Park Auto Parts#
- Open the CollegeParkAutoParts2 application from this lesson
- Create a Part Editor form and design it as follows:
- Add a context menu for the Available Parts list view with the items: Select, Edit..., and Delete
- Configure the context menu so that If the user clicks Select, the behavior would be the same as if the user had double-clicked the item If the user clicks Edit..., the Part Editor dialog box would display with the part in it. The user can then edit any part (year, make, model, category, part name, or unit price) except the part number. Then the user can save the changed part If the user clicks Delete, a message box would warn the user and ask for confirmation with Yes/No answers. If the user clicks Yes, the part would be deleted from the AutoParts list
- Configure the application so that the user can open an order, add new parts to it, or delete parts from it, then save the order
- Extend the application so that the store can also sell items that are, or are not, car-related, such as books, t-shirts, cleaning items, maintenance items (steering oils, brake oils, etc), license plates, etc. Every item in the store should have an item number. The user can enter that item number in the Part # text box and press Tab or Enter. The corresponding item would then be retrieved from the database and displayed on the form. If there is no item with that number, a message box should let the user know
Previous Copyright © 2008 C# Key Next

