Wednesday, April 29, 2009

How to write Gridview data to XML file in .NET

Hi,

One my colleague asked me yesterday , how we could save the Grid View Data to XML File, just i think come to this point and share with you.

Just Read data from the Grid View to DataSet, then we need write that dataset ti XML file.

C#:

DataSet ds = new DataSet("TestDataset");
DataTable dt = new DataTable("TestDataTable");
dt.Columns.Add("Id", System.Type.GetType("System.String"));
ds.Tables.Add(dt);
//Add any number columns here
for (int count = 0; count < GridView1.Rows.Count; count++)
{
DataRow dr = dt.NewRow();
dr[0] = GridView1.Rows[count].Cells[0].Text;
//you can add values to all columns in datatable
dt.Rows.Add(dr);
}
ds.Tables[0].WriteXml("d:\\test2.xml");


VB.NET:

Dim ds As New DataSet("TestDataset")
Dim dt As New DataTable("TestDataTable")
dt.Columns.Add("Id", System.Type.[GetType]("System.String"))
ds.Tables.Add(dt)
'Add any number columns here
For count As Integer = 0 To GridView1.Rows.Count - 1
Dim dr As DataRow = dt.NewRow()
dr(0) = GridView1.Rows(count).Cells(0).Text
'you can add values to all columns in datatable
dt.Rows.Add(dr)
Next
ds.Tables(0).WriteXml("d:\test2.xml")


That's it

Thank you
Keep It watch.

No comments:

Post a Comment