Step1:- Create BindData()
method
protected void BindData()
{
DataTable dt
= new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
int totalRow
= 10;
for (int i
= 0; i < totalRow; i++)
{
dr = dt.NewRow();
dr["Column1"] = "Row" + i;
dr["Column2"] = "Row" + i;
dr["Column3"] = "Row" + i;
dr["Column4"] = 1000 / (i + 1);
dt.Rows.Add(dr);
}
string strXML
= ConvertDataTableToXML(dt);
}
Step 2:- Create ConvertDataTableToXML() method
public string ConvertDataTableToXML(DataTable dt)
{
MemoryStream ms
= new MemoryStream();
dt.WriteXml(ms, true);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string xml
= sr.ReadToEnd();
sr.Close();
return (xml);
}
Step3:- Complete Code
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo
{
public partial class Default :
System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
protected void BindData()
{
DataTable dt
= new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
int totalRow
= 10;
for (int i
= 0; i < totalRow; i++)
{
dr = dt.NewRow();
dr["Column1"] = "Row" + i;
dr["Column2"] = "Row" + i;
dr["Column3"] = "Row" + i;
dr["Column4"] = 1000 / (i + 1);
dt.Rows.Add(dr);
}
string strXML
= ConvertDataTableToXML(dt);
}
public string ConvertDataTableToXML(DataTable dt)
{
MemoryStream ms
= new MemoryStream();
dt.WriteXml(ms, true);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr
= new StreamReader(ms);
string xml
= sr.ReadToEnd();
sr.Close();
return (xml);
}
}
}
Step4:- Put debugger on ConvertDataTableToXML method
and Run the code
When you run the code, you will get the following error:-
Error states that while creating the DataTable object, you are not
given the DataTable name.
See heighted code.
So, you need to assign a table name to DataTable.
Before
DataTable dt = new DataTable();
After
DataTable dt = new DataTable("Table1");
or
DataTable dt = new DataTable();
dt.TableName = "Table1";
No comments:
Post a Comment