Monday, September 12, 2011

Save,Update and Delete in Xml file in Asp.Net



XML is designed to store and transport data. We can store data in a Xml file or Can use Xml as a databse. Here is and example of how we can use xml file to store data, update data and also delete data in Xml file using Asp.Net and C#.

I am using a Grid View control for saving,updating and deleting data in Xml File

use the following code in your .aspx file. it will create a grid view as needed to operate on xml file



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Eno">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("eno") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("eno") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("ename") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("ename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Eval("eadd") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("eadd") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Eval("esal") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("esal") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton3" runat="server" CommandName="update">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" runat="server" CommandName="cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton5" runat="server" CommandName="save">Save</asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="edit">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="delete">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<EmptyDataTemplate>
No Data Available
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>





using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;



String st = Server.MapPath("emp.xml");
if (Page.IsPostBack == false)
{
if(File.Exists(st)==false)
createxml();
getxml();
}



//Method Creating Xml File if does'nt Exists
private void createxml()
{
DataTable tb = new DataTable("emptable");
tb.Columns.Add("eno", Type.GetType("System.Int32"));
tb.Columns.Add("ename", Type.GetType("System.String"));
tb.Columns.Add("eadd", Type.GetType("System.String"));
tb.Columns.Add("esal", Type.GetType("System.Int32"));
DataRow r = tb.NewRow();
r[0] = 1;
r[1]="Rahul Choudhary";
r[2] ="Chandigarh";
r[3] =12000;
tb.Rows.Add(r);
String st = Server.MapPath("emp.xml");
tb.WriteXml(st);
}

//Method to bind Grid view
private void getxml()
{
String st = Server.MapPath("emp.xml");
DataSet ds = new DataSet();
ds.ReadXml(st);
GridView1.DataSource = ds;
GridView1.DataBind();
}

//Grid View Event to Save Data into Xml File
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "save")
{
String st = Server.MapPath("emp.xml");
DataSet ds = new DataSet();
ds.ReadXml(st);
DataRow r = ds.Tables[0].NewRow();
r[0] = Convert.ToInt32(((TextBox)(GridView1.FooterRow.FindControl("TextBox1"))).Text);
r[1] = ((TextBox)(GridView1.FooterRow.FindControl("TextBox3"))).Text;
r[2] = ((TextBox)(GridView1.FooterRow.FindControl("TextBox5"))).Text;
r[3] = Convert.ToInt32(((TextBox)(GridView1.FooterRow.FindControl("TextBox7"))).Text);
ds.Tables[0].Rows.Add(r);
ds.WriteXml(st);
getxml();
}
}

//Grid View Row Deleting Event to Delete From Xml File
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String st = Server.MapPath("emp.xml");
DataSet ds = new DataSet();
ds.ReadXml(st);
ds.Tables[0].Rows.RemoveAt(e.RowIndex);
ds.WriteXml(st);
getxml();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
getxml();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
getxml();
}

//Grid View row Updating Event to update xml file
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
String st = Server.MapPath("emp.xml");
DataSet ds = new DataSet();
ds.ReadXml(st);
ds.Tables[0].Rows[e.RowIndex][1] = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox2"))).Text;
ds.Tables[0].Rows[e.RowIndex][2] = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox4"))).Text;
ds.Tables[0].Rows[e.RowIndex][3] = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox6"))).Text);
GridView1.EditIndex = -1;
ds.WriteXml(st);
getxml();
}

2 comments :

  1. Public Function GetAll(ByVal Path As String) As DataTable
    Dim dt As New DataTable
    Dim ds As New DataSet
    ds.ReadXml(Path & "/Products.xml")
    Dim dt_ret As DataTable = ds.Tables(0)
    Return dt_ret

    End Function
    Dim ObjXMLData as New BusinessLayer.ItemXML
    dt = ObjXMLData.GetAll(Server.MapPath("/").ToString())
    DataGrid1.DataSource = dt
    DataGrid1.DataBind()

    Public Function Insert(ByVal ProductName As String, ByVal Price As Long, ByVal Path As String) As Long
    Try
    Dim dr As DataRow
    Dim ds As New DataSet
    ds.ReadXml(Path & "/Products.xml")
    dr = ds.Tables(0).NewRow
    dr("ItemID") = CType(ds.Tables(0).Rows(ds.Tables(0).Rows.Count - 1)("ItemID"), Long) + 1
    dr("ProductName") = ProductName
    dr("Price") = Price
    ds.Tables(0).Rows.Add(dr)
    ds.WriteXml(Path & "/Products.xml", XmlWriteMode.WriteSchema)
    Return 1
    Catch ex As Exception
    Return 0
    End Try
    End Function

    Insert function takes 3 parameters (ProductName, Price, Path).
    Item ID will be generated automatically by incrementing the last item ID in XML file by using the code:

    dr("ItemID") = CType(ds.Tables(0).Rows(ds.Tables(0).Rows.Count - 1)("ItemID"), Long) + 1

    ds.Tables(0).Rows.Count -1 gives the last index value of the DataSet object


    For Writing to the XML File, I am using WriteXml method of the DataSet that takes the path of the file as a Parameter.

    Public Function Update(ByVal Item_ID As Long, ByVal ProductName As String, ByVal Price As Long, ByVal Path As String) As Long
    Try
    Dim ds As New DataSet
    ds.ReadXml(Path & "/Products.xml")
    Dim dr As DataRow
    dr = ds.Tables(0).NewRow
    Dim a As Integer
    Dim b As Integer
    For b = 0 To ds.Tables(0).Rows.Count - 1
    If Item_ID = ds.Tables(0).Rows(b)("ItemID") Then

    ds.Tables(0).Rows(b)("ItemID") = Item_ID
    ds.Tables(0).Rows(b)("ProductName") = ProductName
    ds.Tables(0).Rows(b)("Price") = Price
    ds.WriteXml(Path & "/Products.xml", XmlWriteMode.WriteSchema)

    End If
    Next
    Return 1
    Catch ex As Exception
    Return 0
    End Try

    End Function

    ReplyDelete
  2. Update
    Cancel


    Save


    Edit
    Delete





    No Data Available







    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.IO;


    Now Copy paste the Following Code in Your Page_Load Event in .cs File

    String st = Server.MapPath("emp.xml");
    if (Page.IsPostBack == false)
    {
    if(File.Exists(st)==false)
    createxml();
    getxml();
    }

    Now add the following code below the Page_Load Event

    //Method Creating Xml File if does'nt Exists
    private void createxml()
    {
    DataTable tb = new DataTable("emptable");
    tb.Columns.Add("eno", Type.GetType("System.Int32"));
    tb.Columns.Add("ename", Type.GetType("System.String"));
    tb.Columns.Add("eadd", Type.GetType("System.String"));
    tb.Columns.Add("esal", Type.GetType("System.Int32"));
    DataRow r = tb.NewRow();
    r[0] = 1;
    r[1]="Rahul Choudhary";
    r[2] ="Chandigarh";
    r[3] =12000;
    tb.Rows.Add(r);
    String st = Server.MapPath("emp.xml");
    tb.WriteXml(st);
    }

    //Method to bind Grid view
    private void getxml()
    {
    String st = Server.MapPath("emp.xml");
    DataSet ds = new DataSet();
    ds.ReadXml(st);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    }

    //Grid View Event to Save Data into Xml File
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
    if (e.CommandName == "save")
    {
    String st = Server.MapPath("emp.xml");
    DataSet ds = new DataSet();
    ds.ReadXml(st);
    DataRow r = ds.Tables[0].NewRow();
    r[0] = Convert.ToInt32(((TextBox)(GridView1.FooterRow.FindControl("TextBox1"))).Text);
    r[1] = ((TextBox)(GridView1.FooterRow.FindControl("TextBox3"))).Text;
    r[2] = ((TextBox)(GridView1.FooterRow.FindControl("TextBox5"))).Text;
    r[3] = Convert.ToInt32(((TextBox)(GridView1.FooterRow.FindControl("TextBox7"))).Text);
    ds.Tables[0].Rows.Add(r);
    ds.WriteXml(st);
    getxml();
    }
    }

    //Grid View Row Deleting Event to Delete From Xml File
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
    String st = Server.MapPath("emp.xml");
    DataSet ds = new DataSet();
    ds.ReadXml(st);
    ds.Tables[0].Rows.RemoveAt(e.RowIndex);
    ds.WriteXml(st);
    getxml();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
    GridView1.EditIndex = e.NewEditIndex;
    getxml();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
    GridView1.EditIndex = -1;
    getxml();
    }

    //Grid View row Updating Event to update xml file
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    String st = Server.MapPath("emp.xml");
    DataSet ds = new DataSet();
    ds.ReadXml(st);
    ds.Tables[0].Rows[e.RowIndex][1] = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox2"))).Text;
    ds.Tables[0].Rows[e.RowIndex][2] = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox4"))).Text;
    ds.Tables[0].Rows[e.RowIndex][3] = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox6"))).Text);
    GridView1.EditIndex = -1;
    ds.WriteXml(st);
    getxml();
    }

    ReplyDelete