What Are Data Web Controls?

ASP.NET provides a number of controls to accomplish a plethora of potential tasks. One very common task Web developers face is displaying data from some data store, usually a database, on a Web page. ASP.NET contains three controls designed specifically for displaying data on a Web page: the DataGrid, the DataList, and the Repeater. Throughout the rest of this book I will refer to these three controls as the data Web controls.

NOTE

There are ASP.NET Web controls other than the DataGrid, DataList, and Repeater that support data binding, such as the RadioButtonList, CheckBoxList, DropDownList, and ListBox Web controls. However, I will not be referring to these controls as data Web controls. Instead, when discussing these controls, I will refer to the control's name explicitly.


To use the data Web controls, simply add the appropriate control to an ASP.NET Web page and set its properties. If you are using an editor like Visual Studio .NET or the Matrix Web Project, this can be as simple as dragging the control from the toolbar onto the ASP.NET Web page.

Each of the data Web controls contains a DataSource property, which should be set to the data that you wish to have displayed in the data Web control. Realize that the data to be displayed can be data from a database, an XML file, a collection, and other sources. We'll delve into the specifics of the DataSource property and what types of objects can and cannot be used as a DataSource in the next chapter; for now, we'll just demonstrate setting the DataSource to the results of a database query.

After you've set the DataSource property, it's simply a matter of calling the control's DataBind() method. This method call will render the control, turning the dynamic data specified by the DataSource into HTML that can be rendered on the user's browser. Listing 1.1 contains a very simple ASP.NET Web page that illustrates the use of a DataGrid Web control.

Listing 1.1 Displaying Data with a Data Web Control Is Simple!
  1: <%@ import Namespace="System.Data" %>   2: <%@ import Namespace="System.Data.SqlClient" %>   3: <script runat="server">   4:     Sub Page_Load(sender as Object, e as EventArgs)   5:       '1. Create a connection   6:        Const strConnString as String = _   7:              "server=localhost;uid=sa;pwd=;database=pubs"   8:        Dim objConn as New SqlConnection(strConnString)   9:  10:       '2. Create a command object for the query  11:       Const strSQL as String = "SELECT * FROM authors"  12:       Dim objCmd as New SqlCommand(strSQL, objConn)  13:   14:       '3. Create the DataAdapter  15:       Dim objDA as New SqlDataAdapter()  16:       objDA.SelectCommand = objCmd  17:  18:       '4. Populate the DataSet and close the connection  19:       Dim objDS as New DataSet()  20:       objDA.Fill(objDS)  21:       objConn.Close()  22:  23:       'Finally, specify the DataSource and call DataBind()  24:       dgAuthors.DataSource = objDS  25:       dgAuthors.DataBind()  26:     End Sub  27: </script>  28:  29: <asp:datagrid  runat="server" /> 

The SqlConnection object on line 8, objConn, makes a connection to the pubs database. Line 11 specifies a SQL query that grabs all the rows and columns from the authors table. On line 20 the DataSet object objDS is filled with the results from the SQL query, and on line 24 the DataGrid's DataSource property is set to the DataSet objDS.

When theDataGrid's DataBind() method is called (line 25), the DataGrid is rendered. A DataGrid converts each item in the DataSource to a row in an HTML table (via the tr tag); for each field in the current DataSource row, a column in the HTML table is added (via the td tag). If you view the ASP.NET page from Listing 1.1 in a browser, you will note that the HTML emitted by the page is a simple HTML table, as shown in Listing 1.2. A screenshot of what the end user will see in his browser is shown in Figure 1.1.

Figure 1.1. The DataGrid is rendered as a vanilla HTML table.

graphics/01fig01.gif

Listing 1.2 The DataGrid Renders into an HTML table

[View full width]

  1: <table cellspacing="0" rules="all" border="1"  style= "border-collapse: graphics/ccc.gifcollapse;">   2:     <tr>   3:     <td>au_id</td><td>au_lname</td><td>au_fname</td><td>phone</td><td> address</ graphics/ccc.giftd><td>city</td><td>state</td><td>zip</td><td>contract</td>   4:     </tr><tr>   5:         <td>172-32-1176</td><td>White</td><td>Johnson</td><td>408 496-7223 </ graphics/ccc.giftd><td>10932 Bigge Rd.</td><td>Menlo Park</td><td>CA</td><td>94025 </td><td>True</td>    6:     </tr><tr>   7:         <td>213-46-8915</td><td>Green</td><td>Marjorie</td><td>415 986-7020 </ graphics/ccc.giftd><td>309 63rd St. #411</td><td>Oakland</td><td>CA</td><td>94618 </td><td>True</td>   8:     </tr><tr>   9:         <td>238-95-7766</td><td>Carson</td><td>Cheryl</td><td>415 548-7723 </ graphics/ccc.giftd><td>589 Darwin Ln.</td><td>Berkeley</td><td>CA</td><td>94705</td> <td>True</td>  10:     </tr><tr>  11:         <td>267-41-2394</td><td>O'Leary</td><td>Michael</td><td>408 286-2428 </ graphics/ccc.giftd><td>22 Cleveland Av. #14</td><td>San Jose</td><td>CA</td><td>95128 </td><td>True</td>  12:     </tr><tr>  13:         ... some rows omitted for brevity ...  14: </table> 

A Note About the Code Examples

Most of the code examples in this book use data from a Microsoft SQL Server 2000 database. Hence, the code uses the SqlClient data provider, meaning that I will be using classes like SqlConnection, SqlCommand, SqlDataAdapter, SqlDataReader, and so on.

If you are not using Microsoft SQL Server 7.0 or later, you will need to use the OleDb data provider. The code in Listing 1.1 would need to be marginally edited to use the OleDb provider. Specifically, line 2 would need to be changed to

 <%@ import Namespace="System.Data.OleDb" %> 

Furthermore, all objects beginning with the prefix Sql would need to be changed to have the prefix OleDb. For example, line 8 in Listing 1.1 would be changed to

 Dim objConn as New OleDbConnection(strConnString) 

The majority of the code examples use the pubs database, which is a standard sample database that has long been shipped with Microsoft SQL Server.

NOTE

If you do not have access to a copy of Microsoft SQL Server, you might want to consider using Microsoft's MSDE. MSDE is a free, scaled-down version of SQL Server, and includes the pubs database. You can download MSDE from http://asp.net/msde/default.aspx. More information regarding MSDE can be found in the "On the Web" section at the end of this chapter.


Expect to see code examples primarily in Visual Basic .NET. There are some C# code examples as well, though. Personally, I prefer C# over Visual Basic .NET, but it is my estimation that the majority of ASP.NET developers use Visual Basic .NET instead of C#. Furthermore, most developers who know C# likely have had some exposure to Visual Basic at some point in their career, and will find translating from Visual Basic .NET to C# to be relatively painless. For some assistance in converting between the two languages, be sure to read "From VB .NET to C# and Back Again" at http://www.4GuysFromRolla.com/webtech/012702-1.shtml.

Finally, my examples use server-side script blocks as opposed to code-behind pages. Although I like the separation of code and content that code-behind pages provide, I find that code examples are easier to follow if both the code and HTML content can be shown in the same listing. Furthermore, using code-behind Web pages is a pain if you're using any editor other than Visual Studio .NET. Although I own a copy of Visual Studio .NET, I am using the ASP.NET team's fine Web Matrix Editor, which can be downloaded for free at http://www.asp.net/WebMatrix/. In any event, for those using code-behind, converting the code samples from the server-side script model to code-behind is trivial simply place the functions and event handlers in the server-side script block into the code-behind class, and make sure any import directives (such as <%@ import Namespace="Some.Namespace " %>) appear as Implements Some.Namespace (Visual Basic .NET) or using Some.Namespace (C#) in your code-behind file.

Why Do We Need Data Web Controls?

Take a moment to look over Listing 1.1, the resulting HTML in Listing 1.2, and the output in Figure 1.1. Notice that we got quite a bit of HTML markup for just a few lines of code. Although Listing 1.1 might feel like it has a lot of source code, realize that the vast majority of it is the code to make a connection to the database and populate a DataSet. The code needed to actually declare the DataGrid, tie the DataSet to the DataGrid, and then to render the DataGrid comprised an entire three lines of code (lines 24, 25, and 29).

Before ASP.NET broke onto the scene in 2002, Microsoft Web developers were using ASP, henceforth referred to as classic ASP. Classic ASP is still in use today, and is still supported on Microsoft's IIS Web server software; in fact, both classic ASP and ASP.NET Web pages can be served from the same Web server. If you've developed data-driven Web sites using classic ASP, you're no doubt painfully familiar with the script code shown in Listing 1.3.

Listing 1.3 Displaying Database Data Using Classic ASP and VBScript

[View full width]

  1: <%@ LANGUAGE="VBSCRIPT" %>   2: <%   3:   Option Explicit   4:   5:   '1. Create a connection   6:   Const strConnString = "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=pubs; graphics/ccc.gifUser ID=sa;Password=;"   7:   Dim objConn, objRS   8:   Set objConn = Server.CreateObject("ADODB.Connection")   9:   objConn.Open(strConnString)  10:  11:   '2. Populate the Recordset with the SQL query  12:   Const strSQL = "SELECT * FROM authors"  13:   Set objRS = Server.CreateObject("ADODB.Recordset")  14:   objRS.Open strSQL, objConn  15:  16:   'Display a table  17:   Response.Write("<table cellspacing=""0"" border=""1"">")  18:  19:   Dim objColumn  20:   Response.Write("<tr>")  21:   For Each objColumn in objRS.Fields  22:     Response.Write("<td>" & objColumn.Name & "</td>")  23:   Next  24:   Response.Write("</tr>")  25:   26:   Do While Not objRS.EOF  27:     Response.Write("<tr>")  28:     For Each objColumn in objRS.Fields  29:       Response.Write("<td>" & objColumn.Value & "</td>")  30:     Next  31:     Response.Write("</tr>")  32:  33:     objRS.MoveNext  34:   Loop  35:   Response.Write("</table>")  36:  37:   objRS.Close()  38:   Set objRS = Nothing  39:  40:   objConn.Close()  41:   Set objRS = Nothing  42: %> 

The output of the code from Listing 1.3 is identical to that of Listing 1.1, which can be seen in Figure 1.1. A quick comparison of the two listings reveals two important facts:

  1. The classic ASP code (Listing 1.3) requires much more code to render the HTML table than the ASP.NET code using the DataGrid. Compare the 3 lines required in Listing 1.1 to the 15 or so lines needed in Listing 1.3 (lines 20 35).

  2. The classic ASP code tightly intermingles the source code and the HTML markup. For example, on lines 27 31 the Response.Write statements output both HTML markup and data. Compare this to the separation of code and HTML style in Listing 1.1.

Both of these facts illustrate the importance of the data Web controls. The benefits derived from Fact 1 are fairly obvious: less code means less time spent programming. Less time spent programming means fewer opportunities for mistakes, which means fewer bugs in your application. Additionally, the fewer lines of code in an ASP.NET Web page, the easier it is to understand what it is the page is supposed to do. Such code readability is vitally important when debugging!

To understand the importance of Fact 2, which deals with the separation of code and content, imagine for a moment that you are presented with the classic ASP code in Listing 1.3. If you want to change the appearance of the resulting HTML table, you would need to pick through the source code finding the appropriate Response.Write statements. Now, imagine that your company's graphic designer is faced with this challenge!

Making such changes with the DataGrid example in Listing 1.1 is exponentially simpler and less error-prone because of the separation of code and content provided by ASP.NET's Web controls. Notice that the code associated with the DataGrid setting the DataSource and calling DataBind() method occurs in the server-side script block. (For further separation of code and content, this could be placed in a code-behind file.) The HTML specifications for the DataGrid occur in the HTML section (line 29 in Listing 1.1). Although we have not specified any HTML stylistic properties on line 29, we could easily add some. For example, if we want to set each row's background color to #EEEEEE (a light gray), we can replace line 29 in Listing 1.1 with

 <asp:datagrid  runat="server" BackColor="#EEEEEE" /> 

To make this same change in the classic ASP code in Listing 1.3, we'd have to either add a bgcolor attribute to each td tag, (meaning we'd have to alter the Response.Write statements in lines 22 and 29), or add a background-color style attribute to the table tag or the td tags. Clearly, making these changes, which would require picking through source code, is not as easy or as clean as the changes needed with ASP.NET data control.

Now that we've examined why the data Web controls are important, let's look at each of the data Web controls in more detail.



ASP. NET Data Web Controls Kick Start
ASP.NET Data Web Controls Kick Start
ISBN: 0672325012
EAN: 2147483647
Year: 2002
Pages: 111

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