7.1 Fundamentals


At its core , data binding is a very straightforward process. Controls that support data binding expose a property named DataSource and a method called DataBind() . When a page is loaded, the user of the control initializes the DataSource property to some collection of data, such as an array, a DataReader , or a DataSet . When the data source is ready to be read from, the user of the control calls the DataBind() method on the control, at which point the control reads in all the data from the data source, making a local copy of it. When the page is ultimately rendered, the control takes the cached data it retrieved from the data source and renders its contents into the response buffer in whatever format the control is built to provide. Figure 7-1 shows the data binding process for a control.

Figure 7-1. Data Binding Process

graphics/07fig01.gif

As we will see, it is possible to bind many different types of data sources, including simple collection classes and data readers connected to a database. The most common data source to bind is typically a data reader, however, because it is the most efficient means of transferring data from a database into a data-bound control. Several controls support data binding, including simple controls, such as the ListBox , and controls designed exclusively for data binding, such as the DataGrid and Repeater . As an example of a common use of data binding, Listing 7-1 shows a page that contains a DataGrid , which is data-bound to the "authors" table in the "pubs" database in SQL Server. This example uses the IDataReader interface to retrieve the data, and it takes care to invoke the DataBind() method immediately after the data reader is prepared and before it is closed.

Listing 7-1 Binding a DataReader to a DataGrid
 <! File: DataGrid.aspx > <%@Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <script language="C#" runat="server"> protected void Page_Load(Object src, EventArgs e) {   IDbConnection conn =     new SqlConnection("server=.;uid=sa;pwd=;database=Pubs");   IDbCommand cmd = conn.CreateCommand();   cmd.CommandText = "SELECT * FROM Authors";   try   {     conn.Open();     IDataReader reader = cmd.ExecuteReader();     gd1.DataSource = reader;     gd1.DataBind();   }   finally   {     conn.Dispose();   } } </script> <body> <form runat=server>   <asp:DataGrid id="gd1" runat=server /> </form> </body> </html> 


Essential ASP.NET With Examples in C#
Essential ASP.NET With Examples in C#
ISBN: 0201760401
EAN: 2147483647
Year: 2003
Pages: 94
Authors: Fritz Onion

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net