A data grid is the prime candidate to display values
of an XML file. It displays its values as a table, using columns and rows.
|
To display the values of an XML file in a data grid,
once the values have been loaded through a data set, you can use the DataSource
property, in which case you would simply assign the name of the DataSet
variable to the DataGrid control.
|
- Start Microsoft Visual C# or MS Visual Studio .Net and create
a new Windows Forms Application named IntroXML1 with its default
form
- To create an XML file, on the main menu, click Project -> Add New
Item...
- In the Templates list, click XML File (.xml)
- In the Name box, replace the string with employees
- Click Open
- Click the empty line under the first. Type <fullrecord>
- Notice that as soon as you type the > sign, the closing tag is
created. Complete the file as follows:
<?xml version="1.0" encoding="utf-8"?>
<fullrecord>
<employee>
<firstname>Sylvie</firstname>
<lastname>Aronson</lastname>
<salary>25.64</salary>
<gender>Female</gender>
</employee>
<employee>
<firstname>Bertrand</firstname>
<lastname>Yamaguchi</lastname>
<salary>16.38</salary>
<gender>Male</gender>
</employee>
<firstname>Anselme</firstname>
<lastname>Bean</lastname>
<salary>22.82</salary>
<gender>Male</gender>
<employee>
<firstname>Mauricette</firstname>
<lastname>Thomas</lastname>
<salary>18.35</salary>
<gender>Female</gender>
</employee>
<employee>
<firstname>Hermine</firstname>
<lastname>Gray</lastname>
<salary>12.75</salary>
<gender>Female</gender>
</employee>
</fullrecord>
|
- Save the XML file in your bin\Debug folder
- Display the form
- From the Windows Forms section of the Toolbox, click DataGrid and click the form:
- Right-click the form and click View Code
- To use a data set, declare a DataSet pointer in the form outside the
constructor:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace IntroXML1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private DataSet dsEmployees;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
. . .
}
}
|
- Display the form
- Double-click any empty area on the form and implement its Load event
as follows:
private void Form1_Load(object sender, System.EventArgs e)
{
this.dsEmployees = new DataSet("employees");
this.dsEmployees.ReadXml("employees.xml");
this.dataGrid1.DataSource = this.dsEmployees;
this.dataGrid1.DataMember = "employee";
}
|
- Test the application
- Close the form
|
|
|