- Start Visual C++ .NET and create a new Windows Forms Application
named VideoCollection1
- To create a new XML file, on the main menu, click Project -> Add
New Item...
- In the Templates section, click XML File (.xml)
- In the File Name box, type videos and press Enter
- Initialize the file as follows:
<?xml version="1.0" encoding="utf-8"?>
<videos>
<video>
<title>Fatal Attraction</title>
<director>Adrian Lyne</director>
<copyright>1987</copyright>
<length>120 Min</length>
<rating>R</rating>
</video>
</videos>
|
- Design the form as follows:
|
Control |
Text |
Name |
Other |
Label |
Video Title: |
|
|
TextBox |
|
txtTitle |
|
Label |
Director: |
|
|
TextBox |
|
txtDirector |
|
Label |
(c) Year: |
|
TextAlign: Right |
TextBox |
|
txtYear |
|
Label |
Length: |
|
|
TextBox |
|
txtLength |
|
Label |
Rating: |
|
|
TextBox |
|
txtRating |
|
Button |
New Record |
btnNewRecord |
|
Button |
Close |
btnClose |
|
|
- Double-click each of the buttons and implement their events as
follows:
private: System::Void btnNewRecord_Click(System::Object * sender, System::EventArgs * e)
{
// We will use a DataSet variable to access the file
DataSet* dsVideos = new DataSet;
// Open the XML file
dsVideos->ReadXml(S"videos.xml");
// We will use a DataTable variable to locate a table from the DataSet
DataTable *dtbVideos = new DataTable;
// Retrieve the first table of the DataSet and put it in our DataTable
dtbVideos = dsVideos->Tables->Item[0];
// We will use a DataRow variable for a record
DataRow __gc *drwVideos;
// Initialize our DataRow with the new record of the table
drwVideos = dtbVideos->NewRow();
// Create an entry in the record for each element of the XML File
drwVideos->Item[S"title"] = this->txtTitle->Text;
drwVideos->Item[S"director"] = this->txtDirector->Text;
drwVideos->Item[S"copyright"] = this->txtYear->Text;
drwVideos->Item[S"length"] = this->txtLength->Text;
drwVideos->Item[S"rating"] = this->txtRating->Text;
// Add the new record to the DataTable
dtbVideos->Rows->Add(drwVideos);
// Update the XML file
dsVideos->WriteXml(S"videos.xml");
// Empty each control of the form in case the user
// wants to create a new record
this->txtTitle->Text = S"";
this->txtDirector->Text = S"";
this->txtYear->Text = S"";
this->txtLength->Text = S"";
this->txtRating->Text = S"";
// Give focus to the first control that can be updated
this->txtTitle->Focus();
}
private: System::Void btnClose_Click(System::Object * sender, System::EventArgs * e)
{
Close();
}
|
- Execute the application. Create a new record
|