Click here to Skip to main content
15,892,005 members
Articles / Web Development / ASP.NET

Edit XML files using a GridView

Rate me:
Please Sign up or sign in to vote.
4.00/5 (10 votes)
3 Apr 2007CPOL3 min read 130.3K   1.7K   52   20
Editing XML files using a GridView.

Screenshot - 027_edit_xml.jpg

Introduction

This short article shows how to edit XML files using a GridView control. Additionally, the user may create new records using some text fields and a button.

The XML document

Let's take a look at the structure of the XML file:

XML
<?xml version="1.0" standalone="yes"?>
<Mitarbeiter>
  <ma>
    <id>1</id>
    <name>Florian 1</name>
    <phone>345</phone>
  </ma>
  ...
</Mitarbeiter>

The document contains some records holding personal data. Each record has an ID, name, and a phone number.

The web form

First, we need some controls for the web form. We need a GridView to display, edit, and delete records from the XML file. The GridView will contain two command fields: ShowEditButton and SchowDeleteButton. To create new entries, I will use three TextBox fields for the columns of the record and a Button. Here is the code for the form:

ASP.NET
<%@ Page Language="VB" AutoEventWireup="false" 
  CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>
        <br />
        <br />
        <br />
        <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtTel" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Button" /></div>
    </form>
</body>
</html>

Page_Load and PageIndexChanging

In the PageLoad event, I have to bind the XML file to the GridView. To do this, I created a routine BindGrid() as I need to bind the GridView multiple times. In the BindGrid method, PhysicalApplicationPath is used to get the complete path to the XML file. Here is the code:

VB
Protected Sub Page_Load(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles Me.Load
   If Page.IsPostBack = False Then
      BindGrid()
   End If
End Sub

Sub BindGrid()
   Dim oDs As New DataSet
   oDs.ReadXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   GridView1.DataSource = oDs
   GridView1.DataBind()
End Sub

Next, I have to create an event handler to implement paging for the GridView. This is as easy as setting the PageIndex for the GridView to e.NewPageIndex.

VB
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, _
         ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) _
         Handles GridView1.PageIndexChanging
   GridView1.PageIndex = e.NewPageIndex
   BindGrid()
End Sub

Deleting records

To delete records from the file is easy. I assign the DataSource from the GridView to a DataSet object. Then I delete the record the user has selected using the DeleteButton from the GridView. Lastly, I update the XML file and call BindGrid().

VB
Protected Sub GridView1_RowDeleting(ByVal sender As Object, _
       ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) _
       Handles GridView1.RowDeleting
   BindGrid()
   Dim oDs As DataSet = GridView1.DataSource
   oDs.Tables(0).Rows(GridView1.Rows(e.RowIndex).DataItemIndex).Delete()
   oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   BindGrid()
End Sub

Updating records

Updating records is a little bit more work. First, I need to set the EditIndex for the GridView using e.NewEditIndex and call BindGrid again. This has to be done in the RowEditing event:

VB
Protected Sub GridView1_RowEditing(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) _
        Handles GridView1.RowEditing
   GridView1.EditIndex = e.NewEditIndex
   BindGrid()
End Sub

Then, I implement the RowCancelingEvent. Very simple: I just have to set the EditIndex to -1 and bind the GridView.

VB
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, _
       ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) _
       Handles GridView1.RowCancelingEdit
   GridView1.EditIndex = -1
   BindGrid()
End Sub

Now I need to create the code for the RowUpdating event. When this event fires, I have to get the changed values for the record from the GridView controls into temporary variables. This is done using a cast (CType) from cells to textboxes. Using the method .Text returns the current value of the control. Maybe, using FindControl is much better. Anyway, here is the code:

VB
Protected Sub GridView1_RowUpdating(ByVal sender As Object, _
         ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) _
         Handles GridView1.RowUpdating
   ' Get the new values from the GridView controls
   Dim i As Integer = GridView1.Rows(e.RowIndex).DataItemIndex
   Dim strId As String = CType(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text
   Dim strName As String = CType(GridView1.Rows(e.RowIndex).Cells(3).Controls(0), TextBox).Text
   Dim strTel As String = CType(GridView1.Rows(e.RowIndex).Cells(4).Controls(0), TextBox).Text
   GridView1.EditIndex = -1
   BindGrid()
   ' Update the XML file using the new values

   Dim oDs As DataSet = GridView1.DataSource
   oDs.Tables(0).Rows(i).Item(0) = strId
   oDs.Tables(0).Rows(i).Item(1) = strName
   oDs.Tables(0).Rows(i).Item(2) = strTel
   oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   BindGrid()
End Sub 

When I get the changed values, I reset the EditIndex to -1 and bind the GridView. Then, I assign the DataSource from the GridView to a DataSet and update the values in the DataSet. Lastly, the new DataSet is written to the XML file.

Creating new records

Lastly, I have to create new records. To do this, I use three TextBoxes and a Button. When the button is clicked, I create a DataSet from the DataSource of the GridView. Next, I call the method Tables(0).NewRow and assign the values to the created DataRow. In the end, I Add the new DataRow to the DataSet and write the XML file using oDs.WriteXml.

VB
Protected Sub Button1_Click(ByVal sender As Object, _
           ByVal e As System.EventArgs) Handles Button1.Click
   BindGrid()
   Dim oDs As DataSet = GridView1.DataSource
   Dim oDr As DataRow = oDs.Tables(0).NewRow
   oDr("id") = txtId.Text
   oDr("name") = txtName.Text
   oDr("phone") = txtTel.Text
   oDs.Tables(0).Rows.Add(oDr)
   oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   BindGrid()
End Sub

Creating new records

That's it - storing data in XML files is very easy. It is also great for deployment as we can just copy the file to the desired location. But, a short warning about this solution: it does not support transactions. The last one who stores the file will win!!!

Maybe you are interested in a screen-cast about editing XML using a GridView: http://dotnet-visions.de.z.seekdotnet.com/blog/index.php?entry=entry061207-022305 (in German only).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Germany Germany
Florian works as consultant for change- and configuration management for about 7 years. In this environment he is often forced to work with unix, perl and shell scripts.

For more information about change- and configuration management (espacially Serena Dimensions) visit: www.venco.de

For video tutorials about asp.net, ajax, gridviews, ... (in german) visit: www.siore.com

Comments and Discussions

 
GeneralMy vote of 5 Pin
Syed J Hashmi11-Apr-15 20:11
Syed J Hashmi11-Apr-15 20:11 
QuestionTextBox size Pin
Member 234235527-May-12 22:30
Member 234235527-May-12 22:30 
GeneralMy vote of 5 Pin
omegammx210-May-12 12:01
omegammx210-May-12 12:01 
QuestionWhy does this code hit my app_code data? Pin
zadoka29-Aug-11 8:00
zadoka29-Aug-11 8:00 
GeneralSorting column and add data to the top of the row Pin
Member 784935618-Apr-11 2:52
Member 784935618-Apr-11 2:52 
QuestionProblem with writing in XML File Pin
Rakino15-Jul-09 22:35
Rakino15-Jul-09 22:35 
GeneralC# Version Pin
Alavri17-May-09 19:44
Alavri17-May-09 19:44 
GeneralRe: C# Version Pin
priyul13-Jan-10 5:14
priyul13-Jan-10 5:14 
GeneralRe: C# Version Pin
a4985058-Feb-10 9:09
a4985058-Feb-10 9:09 
GeneralRe: C# Version Pin
regeter1-Oct-13 3:39
regeter1-Oct-13 3:39 
Generalthanks Pin
ashuangrish28-Jan-09 20:37
ashuangrish28-Jan-09 20:37 
Generalsorting Pin
zamkinos18-Jan-09 1:05
zamkinos18-Jan-09 1:05 
GeneralThank You Pin
whereissami18-Nov-08 22:19
whereissami18-Nov-08 22:19 
Generalvery good Pin
Antonio Dominici S.20-May-08 17:50
Antonio Dominici S.20-May-08 17:50 
Questioncouldnot save the changes to the database using the grid view in asp.net 2.0 Pin
scrapper23-Apr-08 0:02
scrapper23-Apr-08 0:02 
hi,
I am editing the database using the grid view. But while updating its showing an error like "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
Please help me to clear this... my code snippet is::

protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

string name, address, phone;
TextBox t1 = (TextBox)(gv1.Rows[e.RowIndex].Cells[2].Controls[0]);
TextBox t2 = (TextBox)(gv1.Rows[e.RowIndex].Cells[3].Controls[0]);
TextBox t3 = (TextBox)(gv1.Rows[e.RowIndex].Cells[4].Controls[0]);
name = t1.Text;
address = t2.Text;
phone = t3.Text;
gv1.EditIndex = -1;
SqlConnection con = new SqlConnection("server=PC021378\\SQLEXPRESS;Database=master;User ID=sa; password=user");
con.Open();
SqlCommand com = new SqlCommand("select * from doctor", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet dset = new DataSet();
sda.Fill(dset);
gv1.DataSource = dset;
gv1.DataBind();
SqlCommandBuilder cmb = new SqlCommandBuilder(sda);
cmb.GetUpdateCommand(); //Error comes here
dset.Tables[0].Rows[0][1] = name;
dset.Tables[0].Rows[0][2]= address;
dset.Tables[0].Rows[0][3] = phone;
sda.Update(dset);
gv1.DataBind();

}

Help me please
QuestionMultiple Users Deleting Rows Pin
gandalf_lives15-Apr-08 3:54
gandalf_lives15-Apr-08 3:54 
QuestionHow to load multiple level XML file and update? Pin
machewd7-Oct-07 14:57
machewd7-Oct-07 14:57 
Generalthankyouby far the most easy to understand Pin
assasinatedbunny4-Oct-07 8:31
assasinatedbunny4-Oct-07 8:31 
GeneralRe: thankyouby far the most easy to understand Pin
fstrahberger5-Oct-07 20:29
fstrahberger5-Oct-07 20:29 
Questionturkish character problem? Pin
umurlu26-Apr-07 3:16
umurlu26-Apr-07 3:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.