How to CRUD in XML in Asp.Net

Description:- 

GridView control is a successor to the ASP.NET 1.X DataGrid control. It provides more flexibility in displaying and working with data from your database in comparison with any other controls. The GridView control enables you to connect to a datasource and display data is tabular format, however you have bunch of options to customize the look and feel. When it is rendered on the page, generally it is implemented through <table> HTML tag. 

Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properites of <tahle> tag.
 
Behavior Properties of the GridView Control
AllowPaging
true/false. Indicate whether the control should support paging.
AllowSorting
true/false. Indicate whether the control should support sorting.
SortExpression
Gets the current sort expression (field name) that determines the order of the row.
SortDirection
Gets the sorting direction of the column sorted currently (Ascending/Descending).
DataSource
Gets or sets the data source object that contains the data to populate the control.
DataSourceID
Indicate the bound data source control to use (Generally used when we are using SqlDataSource or AccessDataSource to bind the data, See 1st Grid example).
AutoGenerateEditButton
true/false. Indicates whether a separate column should be added to edit the record.
AutoGenerateDeleteButton
true/false. Indicates whether a separate column should be added to delete the record.
AutoGenerateSelectButton
true/false. Indicate whether a separate column should be added to selecat a particular record.
AutoGenerateColumns
true/false. Indicate whether columns are automatically created for each field of the data source. The default is true.

Style Properties of the GridView Control
AlternatingRowStyle
Defines the style properties for every alternate row in the GridView.
EditRowStyle
Defines the style properties for the row in EditView (When you click Edit button for a row, the row will appear in this style).
RowStyle
Defines the style properties of the rows of the GridView.
PagerStyle
Defines the style properties of Pager of the GridView. (If AllowPaging=true, the page number row appears in this style)
EmptyDataRowStyle
Defines the style properties of the empty row, which appears if there is no records in the data source.
HeaderStyle
Defines the style properties of the header of the GridView. (The column header appears in this style.)
FooterStyle
Defines the style properties of the footer of GridView.

Appearance Properties of the GridView Control
CellPadding
Indicates the space in pixel between the cells and the border of the GridView.
CellSpacing
Indicates the space in pixel between cells.
GridLines
Both/Horizontal/Vertical/None. Indicates whether GrdiLines should appear or not, if yes Horizontal, Vertical or Both.
HorizontalAlign
Indicates the horizontal align of the GridView.
EmptyDataText
Indicates the text to appear when there is no record in the data source.
ShowFooter
Indicates whether the footer should appear or not.
ShowHeader
Indicates whether the header should appear or not. (The column name of the GridView)
BackImageUrl
Indicates the location of the image that should display as a background of the GridView.
Caption
Gets or sets the caption of the GridView.
CaptionAlign
left/center/right. Gets or sets the horizontal position of the GridView caption.

State Properties of GridView Control
Columns
Gets the collection of objects that represent the columns in the GridView.
EditIndex
Gets or sets the 0-based index that identifies the row currently to be edited.
FooterRow
Returns a GridViewRow object that represents the footer of the GridView.
HeaderRow
Returns a GridViewRow object that represents the header of the GridView.
PageCount
Gets the number of the pages required to display the reocrds of the data source.
PageIndex
Gets or sets the 0-based page index.
PageIndex
Gets or sets the number of records to display in one page of GridView.
Rows
Gets a collection of GridViewRow objects that represents the currently displayed rows in the GridView.
DataKeyNames
Gets an array that contains the names of the primary key field of the currently displayed rows in the GridView.
DataKeys
Gets a collection of DataKey objects that represent the value of the primary key fields set in DataKeyNames property of

Events associated with GridView Control 
PageIndexChanging, PageIndexChanged
Both events occur when the page link is clicked. They fire before and after GridView handles the paging operation respectively.
RowCancelingEdit
Fires when Cancel button is clicked in Edit mode of GridView.
RowCommand
Fires when a button is clicked on any row of GridView.
RowCreated
Fires when a new row is created in GridView.
RowDataBound
Fires when row is bound to the data in GridView.
RowDeleting,RowDeleted
Both events fires when Delete button of a row is clicked. They fire before and after GridView handles deleting operaton of the row respectively.
RowEditing
Fires when a Edit button of a row is clicked but before the GridView hanldes the Edit operation.
RowUpdating, RowUpdated
Both events fire when a update button of a row is clicked. They fire before and after GridView control update operation respectively.
Sorting, Sorted
Both events fire when column header link is clicked. They fire before and after the GridView handler the Sort operation respectively.

Create your Webpage and Design Like Below.

<div>
   <asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="false" ShowFooter="true"
      Style="margin-left: 113px" Width="1049px" OnRowCommand="gvEmployee_OnRowCommand"
      OnRowCancelingEdit="gvEmployee_RowCancelingEdit" OnRowDeleting="gvEmployee_RowDeleting"
      OnRowEditing="gvEmployee_RowEditing" OnRowUpdating="gvEmployee_RowUpdating" OnPageIndexChanging="gvEmployee_PageIndexChanging">
      <Columns>
         <asp:TemplateField HeaderText="Employee ID" HeaderStyle-Width="100px">
            <ItemTemplate>
               <asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"empid") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
               <asp:TextBox ID="txtAddEmpID" runat="server"></asp:TextBox>
            </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Name" HeaderStyle-Width="100px">
            <EditItemTemplate>
               <asp:TextBox ID="txtName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"name") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
               <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"name") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
               <asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
            </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Designation" HeaderStyle-Width="100px">
            <EditItemTemplate>
               <asp:TextBox ID="txtDesignation" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"designation") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
               <asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"designation") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
               <asp:TextBox ID="txtAddDesignation" runat="server"></asp:TextBox>
            </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="City" HeaderStyle-Width="100px">
            <EditItemTemplate>
               <asp:TextBox ID="txtCity" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"city") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
               <asp:Label ID="lblCity" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"city") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
               <asp:TextBox ID="txtAddCity" runat="server"></asp:TextBox>
            </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Country" HeaderStyle-Width="200px">
            <EditItemTemplate>
               <asp:TextBox ID="txtCountry" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"country") %>' TextMode="MultiLine"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
               <asp:Label ID="lblCountry" runat="server" Text='<%#DataBinder.Eval(Container. DataItem,"country") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
               <asp:TextBox ID="txtAddCountry" runat="server"></asp:TextBox>
            </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Action" HeaderStyle-Width="150px">
            <EditItemTemplate>
               <asp:LinkButton ID="lbtnUpdate" CommandName="Update" runat="server">Update</asp:LinkButton>
               <asp:LinkButton ID="lbtnCancel" CommandName="Cancel" runat="server">Cancel</asp:LinkButton>
            </EditItemTemplate>
            <ItemTemplate>
               <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
               <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete">Delete</asp:LinkButton>
            </ItemTemplate>
            <FooterTemplate>
               <asp:LinkButton ID="lbtnAdd" runat="server" CommandName="Add">Add</asp:LinkButton>
            </FooterTemplate>
         </asp:TemplateField>
      </Columns>
      <HeaderStyle BackColor="#666666" Font-Names="Cambria" ForeColor="White" Height="30px" />
      <RowStyle Font-Names="Calibri" />
   </asp:GridView>
</div>

Create New XML File for Inserting, Deleting, Updating.

<?xml version="1.0" standalone="yes"?>
<EmployeeDetails>
   <Employee>
      <empid>1001</empid>
      <name>Umesh</name>
      <designation>Software Engineer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1002</empid>
      <name>Suresh</name>
      <designation>Web Developer</designation>
      <city>New Delhi</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1003</empid>
      <name>Steve</name>
      <designation>Web Developer</designation>
      <city>Bangalore</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1004</empid>
      <name>Karthik</name>
      <designation>Business Analyst</designation>
      <city>New Delhi</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1005</empid>
      <name>Chirag</name>
      <designation>Software developer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1006</empid>
      <name>Jenish</name>
      <designation>Designer</designation>
      <city>Ahmedabad</city>
      <country>Australia</country>
   </Employee>
</EmployeeDetails>

Go to Code behind File and Generate Grid Different Event for Creating new Element, Deleting, Editing and Updating in XML file.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

protected void BindGrid()
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
    if (ds != null && ds.HasChanges())
    {
        gvEmployee.DataSource = ds;
        gvEmployee.DataBind();
    }
    else
    {
        gvEmployee.DataBind();
    }
}

protected void gvEmployee_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("Add"))
    {
        TextBox txtAddEmpID = (TextBox)gvEmployee.FooterRow.FindControl("txtAddEmpID");
        TextBox txtAddName = (TextBox)gvEmployee.FooterRow.FindControl("txtAddName");
        TextBox txtAddDesignation = (TextBox)gvEmployee.FooterRow.FindControl("txtAddDesignation");
        TextBox txtAddCity = (TextBox)gvEmployee.FooterRow.FindControl("txtAddCity");
        TextBox txtAddCountry = (TextBox)gvEmployee.FooterRow.FindControl("txtAddCountry");
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("EmployeeDetails.xml"));
        XmlElement parentelement = xmldoc.CreateElement("Employee");
        XmlElement empid = xmldoc.CreateElement("empid");
        XmlElement name = xmldoc.CreateElement("name");
        XmlElement designation = xmldoc.CreateElement("designation");
        XmlElement city = xmldoc.CreateElement("city");
        XmlElement country = xmldoc.CreateElement("country");
        empid.InnerText = txtAddEmpID.Text;
        name.InnerText = txtAddName.Text;
        designation.InnerText = txtAddDesignation.Text;
        city.InnerText = txtAddCity.Text;
        country.InnerText = txtAddCountry.Text;
        parentelement.AppendChild(empid);
        parentelement.AppendChild(name);
        parentelement.AppendChild(designation);
        parentelement.AppendChild(city);
        parentelement.AppendChild(country);
        xmldoc.DocumentElement.AppendChild(parentelement);
        xmldoc.Save(Server.MapPath("EmployeeDetails.xml"));
        BindGrid();
    }
}

protected void gvEmployee_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvEmployee.EditIndex = e.NewEditIndex;
    BindGrid();
}

protected void gvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    BindGrid();
    DataSet ds = gvEmployee.DataSource as DataSet;
    ds.Tables[0].Rows[gvEmployee.Rows[e.RowIndex].DataItemIndex].Delete();
    ds.WriteXml(Server.MapPath("EmployeeDetails.xml"));
    BindGrid();
}

protected void gvEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int i = gvEmployee.Rows[e.RowIndex].DataItemIndex;
    string Name = (gvEmployee.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text;
    string Designation = (gvEmployee.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox).Text;
    string City = (gvEmployee.Rows[e.RowIndex].FindControl("txtCity") as TextBox).Text;
    string Country = (gvEmployee.Rows[e.RowIndex].FindControl("txtCountry") as TextBox).Text;
    gvEmployee.EditIndex = -1;
    BindGrid();
    DataSet ds = (DataSet)gvEmployee.DataSource;
    ds.Tables[0].Rows[i]["name"] = Name;
    ds.Tables[0].Rows[i]["designation"] = Designation;
    ds.Tables[0].Rows[i]["city"] = City;
    ds.Tables[0].Rows[i]["country"] = Country;
    ds.WriteXml(Server.MapPath("EmployeeDetails.xml"));
    BindGrid();
}

protected void gvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvEmployee.EditIndex = -1;
    BindGrid();
}

protected void gvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvEmployee.PageIndex = e.NewPageIndex;
    BindGrid();
}

Now run your Webpage and Insert record, update record, or delete record in XML file.

Related Posts

Previous
Next Post »

Thanks for comments.....