Introduction
Today virtually all Web sites use a traditional relational database for persistent storage, retrieval and
modification of data. From an eCommerce website like Amazon.com to a news website like CNN.com, all use a
database (like SQL Server, MSAccess or others) for storage. Databases have numerous advantages, such as having a rich
standardized querying language (SQL), providing transaction support, and good performance. Anytime you are building
a professional-grade Web site, or are dealing with large amounts of data, it behooves you to use a database to
store and retrieve the data.
Sometimes, though, for smaller Web sites or for small amounts of data, a database seems like a bit of overkill.
Too, for Web site hosting companies that charge extra to have database support, it might not make sense to pay this
extra fee if you only need to store a tiny bit of persistent information. In this article, I will demonstrate, how
a simple XML file can be used to store, retrieve, modify and even delete records with the help of the DataGrid
Web control. (For an in-depth discussion of the DataGrid, be sure to read Scott Mitchell's
article series, An Extensive Examination of the DataGrid Web Control.)
Below is a sneak-peak of the user interface we'll be building for editing this XML file. Note that by the end of this
article you'll be able to build a means to insert new records in an XML file, as well as update and delete existing records.
Additionally, feel free to check out the live demo.
What is an XML Document?
XML stands for eXtensible Markup Language, and offers a flexible, human-readable format for storing data.
XML is a tag-based language, but unlike HTML, XML offers user-defined tags - that is, you can add tags in an
XML document with any name you choose, you are not limited to a preset number of tags. XML documents, which are
case-sensitive (unlike HTML), have strict rules regarding their formatting. For more information on what XML is be
sure to read the FAQs at the XML FAQ Category on
ASPFAQs.com.
Examining the XML Document We'll be Working With
The code we'll be examining is designed to work with XML documents of the particular structure shown below:
Realize that the code we will be examining is dependent on the XML file's structure. So, if you need to edit or
insert into an XML file with a different structure, you will need to edit the code presented here. (I'll
point out what code sections need to be changed based on the structure of the XML document...)
Examining the Page_Load Event Handler
In the remainder of this article we'll look at the source code for the ASP.NET Web page bit-by-bit. You can download
the complete code at the end of the article. Let's start our examination of the source code with the
Page_Load event handler:
Sub Page_Load(sender as Object, E as EventArgs)
If NOT IsPostBack Then
LoadXML()
End If
End sub
It first checks to see if that the page is not posted back to the server; if it is not it calls
another subroutine, LoadXML(), which loads the XML data into the DataGrid. The affect of this is
that the XML data is loaded into the DataGrid only on the first page visit. Upon subsequent postbacks, the data is
reloaded from the ViewState. To further understand why this is needed, consider reading
Why Your DataGrid's Updates Don't Show Up.
Looking at the LoadXML() Method
The first few lines of the LoadXML() method create a DataSet and populate it with the contents of
the XML file titled sample.xml. This DataSet is then bound to the DataGrid DataGrid1.
Sub LoadXML()
Dim objData as New DataSet
Try
objData.ReadXml(Server.Mappath("sample.xml"))
DataGrid1.Datasource = objData
DataGrid1.Databind()
...
Notice that the DataSet is populated by an XML file through the ReadXml() method. For more information
on this technique be sure to read the previous 4Guys article
XML, the DataSet, and a DataGrid.
Also note that the file, sample.xml, is assumed to be in the same directory as the ASP.NET Web page
this code is placed within. You should change the filename and path to suit the location and filename of the
XML file you want to edit.
If you look at the above code carefully, you will observe that we have used a Try/Catch error-trapping
mechanism. Now, why in the world did we use that for? Because if reading the XML file into our DataSet generates
any error, we can trap it. If an error is raised it is likely because there is no sample.xml.
For production code, you'd likely want to emit some error message in the Catch block. For testing purposes,
though, I simply call the CreateXML() function in the Catch block. This function creates
the sample.xml XML file. (We won't be examining CreateXML() in this article; refer to
the code at the end of the article for more information on this function.)
The closing Catch block looks as follows.
...
Catch
CreateXML
End Try
End sub
Creating the DataGrid
The next step is to create the DataGrid to which the XML data will be bound to. Since this DataGrid will allow for
its items to be deleted and edited, we need to specify that various events trigger appropriate event handlers.
For example, we want the DataGrid's UpdateCommand to have the UpdateXML() event handler
fire, so we add onUpdateCommand="UpdateXML" to our DataGrid's declaration:
Let's take a brief rundown as to how and why these properties were set:
We have set the ID property of the Datagrid to DataGrid1.
By default the Footer of the Datagrid is not displayed, so we set ShowFooter=True since we
will be displaying the interface to add a new item to the DataGrid through the footer.
The AutoGenerateColumns property of the DataGrid is set to False. Now we can use our own
columns to represent each column of our XML document.
The DataKeyField property is set to aid, so it is evident that we will use this
column as our Primary Key ID.
The onXXX properties wire up the DataGrid's events to event handlers
We will examine the event handlers soon enough.
Let us now turn our attention to the Columns of the DataGrid. We'll examine each column one at a time:
We will be using TemplateColumns for each column displayed in the DataGrid. This choice was made because I wanted
to be able to allow the user to add a new record via the DataGrid footer. To customize the footer's appearance, you need
to use a TemplateColumn. (For more information on adding records to a DataGrid via the footer, be sure to read
John Sanborn's article: Adding a New Record to the DataGrid.
In the ItemTemplate for the aid column, the function ShowVal() is called to display
the value of the aid column. The function ShowVal(), shown below, accepts a single
input parameter. This input parameter is then assigned to a variable called lastVarValue. Note
that lastVarValue is declared outside of the ShowVal() function.
Private lastVarValue as Integer
Function ShowVal(a as integer)
lastVarValue = a
Return a
End Function
As each record
in the XML file is being bound to the DataGrid, its aid value will be stored in the lastVarValue
variable. This variable's final value (plus 1) is then assigned to the Text property of the
TextBox Web control in the column's footer.
We have used FooterTemplate to add a textbox in the footer of the DataGrid. The footer of the aid column
will contain a text box called aid_add. For its Text property's value, we take the
value of the lastVarValue variable, convert it into an integer, and then add 1 to it.
Therefore, if the last aid value in the DataGrid was 6, the default aid for the new
record to be added would be 7.
The EditItemTemplate is used when the DataGrid is in the Edit mode. I have designed the DataGrid so that once
the aid of a row is assigned it cannot be changed. Therefore, when in edit mode, rather than
provide a textbox to let the user edit the value I just print the value of current aid row. This is
how a row is made read-only when using TemplateColumns.
The ItemTemplate prints the value of name column for the current row.
The footer for this column contains a TextBox Web control with an ID of name_add.
This column ends with a template to use when the grid is in the edit mode.
Notice that we use a TextBox Web control when the grid is in the edit mode with the currently selected row’s
value for the Name column.
The DataGrid columns for the salary and dept XML fields follow the same pattern as the Name column...
Changes Required For Different XML Files
If you are using a different XML file, you will need to change the columns of the DataGrid so that instead of
columns for aid, name, salary, and dept, there are columns
for the fields in your custom XML document.
There are two columns left for our DataGrid:
An EditCommandColumn, which displays an Update link and allows the user
to edit an existing record, and
A ButtonColumn that displays a Delete button, for deleting an existing record.
The syntax in the DataGrid for these two columns is as follows:
The Delete column's ItemTemplate displays a LinkButton with the text Delete. The CommandName is set
to Delete so that when the Delete button is clicked, a postback will occur and the DataGird's
DeleteCommand event will fire. In the footer of the Delete column we use another LinkButton
to display a button named Add. A user will click this button to insert a new record into the XML file.
Note that the LinkButton's CommandName is set to doAdd.
This sums up our discussion of the columns in the Datagrid. Next we need to look at the DataGrid's event handlers, which
we will do in Part 2 of this article.