Oct 21, 2009

Bind XML to DataGrid

Binding XML to Datagrid :

In this code we’ll create XML and bind it to Datagrid control.
  1. Add XML file to project (By right click on project à Add à Add New Item à XML file)
2. Now create a XML file (Here I have created a file called Students.xml

<students>
<student>
<id>S0001</id>
<name>Deepika</name>
<city>Ahmedabad</city>
</student>
<student>
<id>S0002</id>
<name>Swati</name>
<city>Maninagar</city>
</student>
<student>
<id>S0003</id>
<name>Dhwani</name>
<city>Gandhinagar</city>
</student>
<student>
<id>S0004</id>
<name>Shweta</name>
<city>Rajkot</city>
</student>
</students>
3. Notice that when you have an XML file opened, the XML menu appears.
Click on the XML menu. The Create Schema will provide a graphic interface to draw the schema for the XML file. The Validate XML Schema helps you with determining if the XML content validates against a certain XML schema.
4. VS.NET tries to come up with the schema for the XML file based on its content. You can open up the schema file and graphically edit or change its definition by code.
Double-click on the Students.xsd file.





  1. By default, the Create XML Schema option defines all the fields as String. You can change it in this GUI or directly in the code representing this schema.
  2. Now add a button called “Load XML” to a webform which will populate data to gridview from xml file.
protected void btnload_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet("Students");
ds.ReadXmlSchema(Server.MapPath(".") + "\\Students.xsd");
ds.ReadXml(Server.MapPath(".") + "\\Students.xml");
GridView1.DataSource = ds;
GridView1.DataBind();
}

No comments:

Post a Comment