ASP.
NET data binding
ASP.NET allows powerful feature of data binding, you can bind any server
control to simple properties, collections, expressions and/or methods. When
you use data binding, you have more flexibility when you use data from a
database or other means.
Data Bind controls are container controls.
Controls -> Child Control
Data Binding is binding controls to data from databases. With data binding we
can bind a control to a particular column in a table from the database or we
can bind the whole table to the data grid.
Data binding provides simple, convenient, and powerful way to create a
read/write link between the controls on a form and the data in their
application.
Data binding allows you to take the results of properties, collection, method
calls, and database queries and integrate them with your ASP.NET code. You
can combine data binding with Web control rendering to relieve much of the
programming burden surrounding Web control creation. You can also use
data binding with ADO.NET and Web controls to populate control contents
from SQL select statements or stored procedures.
Data binding uses a special syntax:
<%# %>
The <%#, which instructs ASP.NET to evaluate the expression. The difference
between a data binding tags and a regular code insertion tags <% and %>
becomes apparent when the expression is evaluated. Expressions within the
data binding tags are evaluated only when the DataBind method in the Page
objects or Web control is called.
Data Bind Control can display data in connected and disconnected model.
Following are data bind controls in ASP.NET:
Repeater Control
DataGrid Control
DataList Control
GridView Control
DetailsView
FormView
DropDownList
ListBox
RadioButtonList
CheckBoxList
BulletList
etc.
This article refers to the following Microsoft .NET Framework Class Library
namespaces:
System.Data
System.Data.SqlClient
With ASP.NET data binding, you can bind any server control to simple properties,
collections, expressions and/or methods. When you use data binding, you have
more flexibility when you use data from a database or other means.
This article addresses the following data binding topics:
Data binding essentials
<%# %> Syntax
Page.DataBind() versus Control.DataBind()
Data-bound list controls
Repeater control
DataList control
Binding in list control templates
DataBinder.Eval method
Explicit casting
Data binding essentials
<%# %> Syntax
The following list includes examples of simple data binding from multiple
sources:
Simple property (syntax for a customer):
<%# custID %>
Collection (syntax for an order):
<asp:ListBox id="List1" datasource='<%# myArray %>'
runat="server">
Expression (syntax for a contact):
<%# ( customer.FirstName + " " + customer.LastName ) %>
Method result (syntax for the outstanding balance):
<%# GetBalance(custID) %>
In the preceding examples, the inline <%# %> tags indicate where the
information from a specific data source is to be placed in the .aspx page. The
following data binding example uses a TextBox Web server control:
<asp:textbox id=txt text="<%# custID %>" runat=server />
Page.DataBind() versus Control.DataBind()
After the particular data sources have been determined and set for the objects on
the .aspx page, you must bind the data to these data sources. You can use
the Page.DataBind or the Control.DataBind method to bind the data to the data
sources.
Both methods work similarly. The main difference is that all data sources are
bound to their server controls after the Page.DataBind method is called. No data
is rendered to the control until you explicitly call either the DataBind method of
the Web server control or until you invoke the page-level Page.DataBind method.
Typically, Page.DataBind (or DataBind) is called from the Page_Load event.
Binding Gridview with Eval in ASP.Net C#
Here is short tutorial how to bind Gridview with Eval in ASP.Net C#/VB
Database
For binding the gridview, First have to create a table in Microsoft SQL Server
Database as shown below.
Creating a table
When creating a table make Identity Specification as true for column 'ID'.
Set the table name as
shown below.
Adding a GridView to the Page
Firstly you need to add a GridView control to the Page from the Visual Studio
ToolBox as shown below.
HTML
Below is the sample HTML code,
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Binding Employee Details</title>
</head>
<body>
<form id="form1" runat="server">
<h2 style="color: Maroon;">
Employee Details</h2>
<div>
<asp:GridView ID="grdviewEmployee" runat="server" GridLines="None"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="mt5px">
<b>Name:</b>
<%# Eval("EmployeeName")%>
</div>
<div class="mt5px">
<b>Designation:</b>
<%# Eval("EmployeeDesc")%>
</div>
<div class="mt5px">
<b>Age:</b>
<%# Eval("EmployeeAge")%>
</div>
<div class="mt5px">
<b>Address:</b>
<%# Eval("EmployeeAddress")%>
</div>
<div class="mt5px">
<b>Experience:</b>
<%# Eval("EmployeeExperience")%>
</div>
<div class="mt5px">
----------------------------------------------------</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
STYLE
Below is the sample STYLE code,
<style>
.mt5px
{
margin-top: 5px;
}
</style>
Namespaces
You will need to import the following namespace.
C#
using System.Data.SqlClient;
using System.Data;
Binding of data to GridView from Database using DataSet
Below is the sample code for binding data to DataGridView with Eval from
Database using DataSet in C#/.
C#
public partial class ASPDotNet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillGridView();
}
public void FillGridView()
{
string conString = " server=YOUR SERVER_NAME; database=YOUR
DB_NAME; uid=**; password=****;";
SqlConnection conn = new SqlConnection(conString);
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Employ
ee", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
grdviewEmployee.DataSource = ds;
grdviewEmployee.DataBind();
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
to work with bind in TemplateField syntax in gridview :
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
As you can see, the TemplateField consists of two templates
an ItemTemplate that has a Label whose Text property is set to the value of
the FirstName data field, and an EditItemTemplatewith a TextBox control
whose Text property is also set to the FirstName data field. The databinding
syntax - <%# Bind("fieldName") %> - indicates that the data field fieldName is
bound to the specified Web control property.
To add the LastName data field value to this TemplateField we need to add
another Label Web control in the ItemTemplate and bind its Text property
to LastName. This can be accomplished either by hand or through the
Designer. To do it by hand, simply add the appropriate declarative syntax to
the ItemTemplate:
aspxCopy
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("FirstName") %>'></asp:Label>
<asp:Label ID="Label2" runat="server"
Text='<%# Eval("LastName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Example 3
How to use DataAdapter in asp.net c#
using System;
using System.Data ;
using System.Data.SqlClient ;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs
e)
{
string connectionString =
ConfigurationManager.ConnectionStrings["SQLDbConnection"].ToSt
ring();
SqlConnection connection = new
SqlConnection(connectionString);
DataSet ds = new DataSet ();
string sql = "select pub_name from publishers";
try
{
connection.Open();
SqlDataAdapter adapter = new
SqlDataAdapter(sql,connection );
adapter.Fill(ds);
for (int i = 0;i < ds.Tables[0].Rows.Count
-1;i++)
{
ListBox1.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString
());
}
connection.Close();
}
catch (Exception ex)
{
Label1.Text = "Error in execution " +
ex.ToString();
}
}
}
DataAdapter
DataAdapter represents a set of SQL commands and a Database
connection that are used to fill the DataSet and update the data
source. .NET developers can initialize a new instance of
DataAdapter class using this two constructors DataAdapter() and
DataAdapter(DataAdapter). DataAdapter(DataAdapter) constructor
initialize a new instance of a DataAdapter class from an existing
same type object.
DataAdapter class have many methods such as CloneInternals,
CreateTableMappings, Dispose, Dispose(Boolean),
Equals(Object), Fill(DataSet), Fill(DataTable, IDataReader),
Fill(DataTable[], IDataReader, Int32, Int32), FillSchema(DetaSet,
SchemaType), Finalize, GetFillParameters, GetHashCode,
GetService, GetType, HasTableMappings, OnFillError,
ResetFillLoadOption, ToString, Update etc.
DataAdapter Fill method add or refresh rows in the DataSet to
match those in the data source. Fill(DataTable, IDataReader) uses
DataTable name and specified IDataReader, Fill(DataTable[],
IDataReader, Int32, Int32) overloaded method add or refresh rows
in a specified range in the collection of DataTable objects to match
those in the data source. Fill(DataSet, String, IDataReader, Int32,
Int32) overloaded method uses DataSet and DataTable names.
SqlDataAdapter
If we want to connect a SQL Server Database, we can increase
overall performance by using the SqlDataAdapter along with its
associated SqlCommand and SqlConnection objects.
SqlDataAdapter represent a set of data commands and a
Database connection that are used to fill the DataSet and update a
SQL Server Database. We can initialize a new instance of
SqlDataAdapter class using those constructors SqlDataAdapter(),
SqlDataAdapter(SqlCommand), SqlDataAdapter(String,
SqlConnection), and SqlDataAdapter(String, String).
SqlDataAdapter(SqlCommand) overloaded method require
specified SqlCommand as the SelectCommand property.
SqlDataAdapter(String, SqlConnection) overloaded method require
a SelectCommand and a SqlConnection object.
SqlDataAdapter(String, String) method require a SelectCommand
and a connection string.
SqlDataAdapter class main properties are
AcceptChangesDuringFill, ContinueUpdateOnError,
DeleteCommand, FillLoadOption, InsertCommand,
SelectCommand, TableMappings, UpdateCommand etc.
SqlDataAdapter SelectCommand property get or set a Transact
SQL Statement or stored procedure used to select records.
UpdateCommand property used to update records in the data
source. InsertCommand used to insert new records in the data
source. DeleteCommand delete records from the DataSet.
Following methods are important in SqlDataAdapter class
Dispose(), Fill(DataSet), Fill(DataTable), Fill(DataSet, String),
Fill(Int32, Int32, DataTable[]), FillSchema(DataSet, SchemaType),
Update(DataRow[]), Update(DataSet), Update(DataTable),
Update(DataSet, String) etc.
SqlDataAdapter Fill(DataSet) method add or refresh rows in the
DataSet. Fill(DataTable) overloaded method add or refresh rows in
a specified range in the DataSet to match those in the data source
using DataTable name. Update(DataTable) method update the
values in the database by executing INSERT, UPDATE or
DELETE statement in the specified DataTable.
The following c# ADO.NET example source code describe you
more about SqlDataAdapter.
DataAdapterExample.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Configuration" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender,
System.EventArgs e) {
if (!Page.IsPostBack) {
SqlConnection MyConnection;
SqlCommand MyCommand;
SqlDataAdapter MyAdapter;
DataTable MyTable;
MyConnection = new SqlConnection();
MyConnection.ConnectionString =
ConfigurationManager.ConnectionStrings["AppConn
ectionString1"].ConnectionString;
MyCommand = new SqlCommand();
MyCommand.CommandText = "SELECT TOP
8 * FROM PRODUCTS";
MyCommand.CommandType =
CommandType.Text;
MyCommand.Connection =
MyConnection;
MyTable = new DataTable();
MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand =
MyCommand;
MyAdapter.Fill(MyTable);
GridView1.DataSource =
MyTable.DefaultView;
GridView1.DataBind();
MyAdapter.Dispose();
MyCommand.Dispose();
MyConnection.Dispose();
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataAdapter example: how to use
DataAdapter in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
With gridview
<asp:TemplateField HeaderText="year">
<ItemTemplate>
<asp:TextBox ID="Txt_year" onblur="onlyNumber(this)" runat="server" Text='<
%#Eval("BoundField")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
but my requirement that i use xpath in codebehind
<asp:TextBox ID="Txt_year" onblur="onlyNumber(this)" runat="server" Text='<
%#Eval("BoundField")%>'>
</ItemTemplate>
examples 3
The following examples show how to use the Eval method to bind data
to Repeater control. It requires a data class named Product.
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
The code-behind file loads test data and binds that data to a Repeater control.
public partial class ShowProducts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var products = new List<Product>();
products.Add(new Product() { ProductID = 1, Name = "Bike",
Price = 150.00 });
products.Add(new Product() { ProductID = 2, Name = "Helmet",
Price = 19.99 });
products.Add(new Product() { ProductID = 3, Name = "Tire",
Price = 10.00 });
ProductList.DataSource = products;
ProductList.DataBind();
}
}
In the declarative syntax for the Repeater control, you use the Eval method
with Container.DataItem for the container parameter.
ASP.NET (C#)
<asp:Repeater ID="ProductList" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Name") %> for only <
%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}") %>
<br />
<a href='<%# DataBinder.Eval(Container.DataItem, "ProductID",
"details.asp?id={0}") %>'>See Details</a>
<br />
<br />
</ItemTemplate>
</asp:Repeater>
Or, you can call Eval function and not include the container parameter.
ASP.NET
<asp:Repeater ID="ProductList" runat="server">
<ItemTemplate>
<%# Eval("Name") %> for only <%# Eval("Price", "{0:c}") %>
<br />
<a href='<%# Eval("ProductID", "details.asp?id={0}") %>'>See
Details</a>
<br />
<br />
</ItemTemplate>
</asp:Repeater>
Data-bound list controls
The list controls are special Web server controls that can bind to collections. You
can use these controls to display rows of data in a customized template format.
All list controls expose the DataSource and the DataMember properties, which are
used to bind to collections.
These controls can bind their DataSource property to any collection that supports
the IEnumerable, the ICollection, or the IListSource interface.
Repeater control
The Repeater control is a templated, data-bound list. The Repeater control is
"lookless;" that is, it does not have any built-in layout or styles. Therefore, you
must explicitly declare all HTML layout, formatting, and style tags in the control's
templates.
The following code samples demonstrate how you can use one list control,
the Repeater control, to display data:
NOTE: You must modify the parameters of the connection string as necessary for
your environment.
Inline cod using Visual C# .NET
<%@ Page language="c#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection cnn = new
SqlConnection("server=(local);database=pubs;Integrated
Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from
authors", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "authors");
Repeater1.DataSource = ds.Tables["authors"];
Repeater1.DataBind();
}
</script>
<html>
<body>
<form id="WebForm2" method="post" runat="server">
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
DataList control
The DataList class is a feature-rich, templated, data-bound list. You can modify
the templates to customize this control. Unlike
the Repeater control, DataList supports directional rendering and can optionally
render in an HTML table at run time.
Accessing data
This section describes how to access data from a database and bind the data to
list controls. You can use the DataSet or the DataReader class to obtain data from
a database.
DataSet class
A DataSet contains a complete representation of data, including the table
structure, the relationships between tables, and the ordering of the
data. DataSet classes are flexible enough to store any kind of information from a
database to an Extensible Markup Language (XML) file. DataSet classes are
stateless; that is, you can pass these classes from client to server without tying up
server connection resources. The following code demonstrates how to use
a DataSet to bind data to a control:
NOTE: You must modify the parameters of the connection string as necessary for
your environment.
Visual C# .NET
SqlConnection cnn = new SqlConnection("server=(local);
database=pubs;Integrated
Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from authors",
cnn);
DataSet ds = new DataSet();
da.Fill(ds);
MyRepeater.DataSource = ds;
MyRepeater.DataBind();
Visual J# .NET
SqlConnection cnn = new SqlConnection("server=(local);
database=pubs;Integrated
Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from authors",
cnn);
DataSet ds = new DataSet();
da.Fill(ds);
MyRepeater.set_DataSource(ds);
MyRepeater.DataBind();
DataReader class
Conversely, if you only need to display (and not change) the data that is to be
rendered, a DataReader class may be a better solution. For example, it is better to
use a DataReader for a DropDownList control because the DataReader is a
forward-only data cursor. The following code demonstrates how to use
a SqlDataReader class to bind data to a control:
Visual C# .NET
SqlConnection cnn = new SqlConnection("server=(local);
database=pubs;Integrated
Security=SSPI");
SqlCommand cmd = new SqlCommand("select * from authors", cnn);
cnn.Open();
MyRepeater.DataSource =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
MyRepeater.DataBind();
Visual J# .NET
SqlConnection cnn = new SqlConnection("server=(local);
database=pubs;Integrated
Security=SSPI");
SqlCommand cmd = new SqlCommand("select * from authors", cnn);
cnn.Open();
MyRepeater.set_DataSource(cmd.ExecuteReader(CommandBehavior.Close
Connection));
MyRepeater.DataBind();
To display backend result set (tuple collection) Repeater Control, DataGrid
Control, DataList Control, GridView Control are used.
Repeater Control, DataList Control and FormView Control are unformatted
controls.
DetailsView and FornView controls display single tuple result at a time.
DropDownList, ListBox, RadioButtonList, CheckBoxList and BulletList controls
displays single column values.
TemplateFields and items templates in
gridviewcontrol:
We use TemplateFields when we wish to display ASP.Net controls in a GridView
column. We display ASP.Net controls in a GridView column to provide additional
functionality in the user interface. For example, by placing a DropDownList control in a
GridView column, users will be able to select a list of options from within the Gridview
control interface. Other examples of providing more functionality to the GridView interface
are placing Checkboxes, Labels, Textboxes and Validation controls. A Template field
supports many types of templates and a list of template types is given in the table below.
TemplateType Description
AlternatingItemTemplate The contents of this template are
displayed for every other row
rendered by the GridView
The contents of this template are
EditItemTemplate displayed when a row is selected for
editing
The contents of this template are
FooterTemplate
displayed in the column footer
The contents of this template are
HeaderTemplate
displayed in the column header
The contents of this template are
InsertTemplate displayed when a new data item is
inserted
The contents of this template are
ItemTemplate displayed for every row rendered by
the GridView
We can create TemplateFields in the GridView control using <TemplateField> element.
Steps to create the <TemplateField> element in the GridView control
a. Declare the GridView and set the AutoGenerateColumns property to 'false'.
b. Create a Template column using <asp:TemplateField> tag within the <Columns>
element.
Create within the <asp:TemplateField> element to display value of field as text.
Create <EditItemTemplate> to display TextBox control to modify value of field when
editing the record.
<asp:GridView ID="GridView1" DataSourceId="MyDataSource"
DataKeyNames="Code"
AutoGenerateColumns="false" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true" runat="server">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Eval("Name")%>
<%#Eval("Description")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" Text='<%# Bind("Name")%>'
runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%#Eval("Description")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDesctiption"Text='<%#
Bind("Description")%>'
runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="MyDataSource"
ConnectionString="<%$Connectionstrings:ERPConnectionString
%>"
SelectCommand="SELECT * FROM Sample"
UpdateCommand="Update SAMPLE SET
Name=@Name,Description=@Description Where Code=@Code"
DeleteCommand="Delete SAMPLE Where Code=@Code"
runat="server"/>
Configure the SqlDataSource control and set the SelectCommand and UpdateCommand
properties to display and update records from the Sample Table.
Observe that we have created two Template fields the GridView control. The first
TemplateField is used to display and edit the value of the 'Name' field in the SAMPLE
table. The second TemplateField is used to display and edit the value of the 'Description'
field in the SAMPLE table. The contents of the ItemTemplate are displayed when a row is
in normal mode and the contents of the EditItemTemplate are displayed when a row is in
edit mode
Binding XML data to Gridview Template Field
With ASP.NET data binding, you can bind any server control to simple properties,
collections, expressions and/or methods. When you use data binding, you have more
flexibility when you use data from a database or other means.
Data binding essentials
<%# %> Syntax
ASP.NET introduces a new declarative syntax, <%# %>. This syntax is the basis for
using data binding in an .aspx page. All data binding expressions must be contained
within these characters.
let us start Binding XML data to Gridview Template Field using dataset
ReadXml method is used to fill it with schema and data.
using order.xml file to bind the data into gridview template field
<?xml version=”1.0″?>
<orderReport>
<report>
<orderCode>1234</orderCode>
<Date>21321</Date>
<Location>dada</Location>
<Content>asad</Content>
<Count>12</Count>
</report>
<report>
<orderCode>1002</orderCode>
<Date>09-02-2009</Date>
<Location>chennai</Location>
<Content>plasma</Content>
<Count>5</Count>
</report>
<report>
<orderCode>1003</orderCode>
<Date>06-03-2008</Date>
<Location>pune</Location>
<Content>Bikes</Content>
<Count>10</Count>
</report>
</orderReport>
step1: Open visual studio –> File –> New –> Website –>choose visual studio
template asp.net website–>ok
step2: Drag the Gridview control into default.aspx page
keep Gridview AutoGeneratecolumns property is false
step3: goto gridview Tasks –> click Edit columns.. –> choose TemplateField –>click
add button (templateField is added to
gridview) –>click OK see below figures
gridviewTemplate field
Gridview edit Template field
now again goto Gridview Tasks click Edit Templates see below figure
gridview itemtemplate
step4: now add table with 1 row and 4 columns inside item template of gridview add
four labels to that columns of the table inside item template.
gridview edit databinding
step5: Bind xml values (ordercode,location,content binding 3 column fields only out
of 5 you can bind 5 fields ). To bind
values ( see above figure click label edit DataBindings)
gridview binding value
similarly bind location field, content field. There are three labels in my gridview
label1 is binded as Eval(“orderCode”)
label2 is binded as Eval(“Loaction”)
label3 is binded as Eval(“Content”)
above binding names must be same as xml data i.e
<report>
<orderCode>1234</orderCode> // this orderCode is Eval(“orderCode”)
<Date>21321</Date>
<Location>dada</Location> //this Location is Eval(“Location”)
<Content>asad</Content> //this content is Eval(“Content”)
<Count>12</Count>
</report>
step 6: After binding all values click End Template Editing.
gridview EndTemplate Field
now see the design view of gridview
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID=”Label1″ runat=”server” Text='<%# Eval(“orderCode”)
%>’></asp:Label>
</td>
<td>
<asp:Label ID=”Label2″ runat=”server” Text='<%# Eval(“Location”)
%>’></asp:Label>
</td>
<td>
<asp:Label ID=”Label3″ runat=”server” Text='<%# Eval(“Content”)
%>’></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Write the code to display the data
Note:1) my xml file name is order.xml it doesn’t contain any folders.sogive the
path as Server.MapPath(“order.xml”)
2) If the order.xml inside the folder name of orderDetails then change the path as
Server.MapPath(“orderDetails/order.xml”)
sample code look like in Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
txtDateOfReport.Text = DateTime.Now.ToShortDateString();
DataSet objDs = new DataSet();
//it does not contain any folder
objDs.ReadXml(Server.MapPath(“order.xml”));
//Inside orderDetails is foldername contain order.xml file
//objDs.ReadXml(Server.MapPath(“orderDetails/order.xml”));
GridView1.DataSource = objDs.Tables[0].DefaultView;
GridView1.DataBind();