<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<title>Binding a DataReader to a DataGrid Control</title>
<link rel="stylesheet" href="/shared/netdemos.css">
<script language="C#" runat="server" src="~/shared/fetchData_sql.cs" />
<script language="C#" runat="server">
protected void Page_Load ( object src, EventArgs e ) {
// specify the data source
SqlConnection myConn = new SqlConnection ( getConnection ( "aspnet" ) );
// define the command query
SqlCommand myCmd = new SqlCommand ( "SELECT * FROM titles", myConn );
// open the connection
myConn.Open ( );
// bind the datagrid to the reader
myGrid.DataSource = myCmd.ExecuteReader ( CommandBehavior.CloseConnection );
myGrid.DataBind ( );
// close the connection
myConn.Close ( );
}
</script>
<body>
<!-- #include virtual="~/shared/top.inc -->
<div class="header"><h2>Binding a <span class="hilite">DataReader</span> to a <span class="hilite">DataGrid</span> Control</h2></div>
<!-- #include virtual="~/shared/viewsrc_top.inc" -->
<hr size=1 width=92%>
<p align="center">
<form runat="server">
<asp:datagrid id="myGrid" runat="server"
width="90%" cellpadding=5 font-size="10pt"
gridlines="horizontal"
itemstyle-verticalalign="top"
autogeneratecolumns=false>
<headerstyle backcolor="slategray"
forecolor="ivory"
height=25pt font-bold />
<columns>
<asp:templatecolumn>
<itemtemplate>
<a href='details_title.aspx?titleid=<%# Eval ( "title_id" ) %>'>
<img width=60 align="top" alt="Click for details" border=0
src='<%# Eval ( "title_id", "/shared/images/title-{0}.gif" ) %>'
style="box-shadow: 3px 3px 3px gray">
</a>
</itemtemplate>
</asp:templatecolumn>
<asp:boundcolumn headertext="Title"
datafield="title" />
<asp:boundcolumn headertext="Notes"
datafield="notes" />
<asp:boundcolumn headertext="Publication"
datafield="pubdate"
dataformatstring="{0:d}" />
<asp:boundcolumn headertext="Price"
datafield="price"
dataformatstring="{0:c}"
itemstyle-horizontalalign="right" />
</columns>
</asp:datagrid>
</form>
</p>
<hr size=1 width=92%>
<!-- #include virtual="~/shared/viewsrc.inc" -->
</body>
</html>