Save data from DataGrid to XML : DataGrid « XML « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="DataSetXml" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <H2>Data from SQL Server</H2>
      <asp:DataGrid id="Datagrid1" runat="server" HeaderStyle-Font-Bold="true"></asp:DataGrid><BR>
      <BR>
      <H2>Data from the XML file</H2>
      <asp:DataGrid id="Datagrid2" runat="server" HeaderStyle-Font-Bold="true"></asp:DataGrid>
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;
using System.Web.Configuration;

public partial class DataSetXml : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
    string sql = "SELECT TOP 5 EmployeeID, TitleOfCourtesy, LastName, FirstName FROM Employees";
    SqlConnection conn = new SqlConnection(connectionString);
    SqlDataAdapter da = new SqlDataAdapter(sql, conn);
    DataSet ds = new DataSet();

    da.Fill(ds, "Employees");
    Datagrid1.DataSource = ds.Tables["Employees"];
    Datagrid1.DataBind();

    string xmlFile = Server.MapPath("Employees.xml");
    ds.WriteXml(xmlFile, XmlWriteMode.WriteSchema);

    DataSet dsXml = new DataSet();
    dsXml.ReadXml(xmlFile);

    Datagrid2.DataSource = dsXml.Tables["Employees"];
    Datagrid2.DataBind();
    }
}

File: Web.config

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <appSettings/>
  <connectionStrings>
    <add name="Northwind" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI"/>
  </connectionStrings>
  
</configuration>








25.1.DataGrid
25.1.1.Use DataGrid to edit data in XML (VB.net)
25.1.2.Binding XML data to DataGrid (VB.net)
25.1.3.Save data from DataGrid to XML