Hi, in this article you are going to know how to read data form XML file and binding into grid view and updating the new record in the same XML file. Using Methods ReadXml() and WriteXml() Methods. In this article you also come to know how to write the data from DataSet to XML file.
Introduction
Hi in this Article u r going to knw how to read data form XML file and binding into grid view and Updating the new record in the same XML file. Using Methods ReadXml () and WriteXml () Methods. In this article u also come to know how to write the data from DataSet to XML file.
Namespace: System.Xml is need to add in ur application.
Procedure:
- Reading the content of the XML file into Dataset and then bind it to Gridview.
- Add the new record to this Dataset through grid view.
- Write the Data from the Dataset to XML file.
1>Reading XML File.
Using ReadXml() Method you can read the content of the file. In this article file (data.xml) contain user information with 3 tags( Id, Name, Designation).
Code:
if
(!(IsPostBack)){
DataSet ds = new DataSet();ds.ReadXml(Server.MapPath(
"data.xml"));Session[
"Data"] = ds.Tables[0];Bind();
// binding the data to gridView(id=gvdata)}
In the above Code reading the content of xml file is read into DataSet ds. And bind to GridView by calling Bind() function.
2>Adding new record.
Steps:1. In this example I am adding new record in gridview and update the record to the DataTable which is the DataSource for the GridView.
2. Code:
DataTable
dt = Session["Data"] as DataTable;DataRow dr = dt.NewRow(); // creating new row to add new record into datatableTextBox t1 = (TextBox)gvData.FooterRow.FindControl("txtId");TextBox t2 = (TextBox)gvData.FooterRow.FindControl("txtName");TextBox t3 = (TextBox)gvData.FooterRow.FindControl("txtDsng");dr[0] = t1.Text;
dr[1] = t2.Text;
dr[2] = t3.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();
3>Writing the containt of the data from DataTable to XML File(data.xml)
Steps:
1. Here DataTable has new record which has been added newly.
2. Using WriteXml() Method we can Update the XML File.
3. Code:
dt.WriteXml(Server.MapPath(
"data.xml"));// updating the new record into XML File
Session[
"Data"] = dt;Bind();
// binding the data to gridviewgvData.EditIndex = -1;
Conclusion:
Hope this article make more sense about accessing the data from XML file in ASP.net using C#.
ThankYou.