Customizing Data-Binding Output in Templates

Until now, the majority of the examples we've examined that have used data-binding syntax within templates have simply output a particular value from the current item from the DataSource. The syntax for this has looked like either

 <%# Container.DataItem %> 

or

 <%# DataBinder.Eval(Container.DataItem, "SomePropertyOrValue") %> 

depending on the DataSource. The former example would be used if the DataSource is a string array, and the latter example might be used if the DataSource is a DataSet, DataReader, or some other complex object.

If we limit ourselves to such simple data binding, templates are only useful for customizing the look and feel of the data Web control's output, and little else. That is, because data-binding syntax is used only within templates, if the data binding is limited only to re-emitting the DataSource values as is, then why would one need to use a template, other than to specify the placement of HTML markup and data?

In this section, we will examine how to customize the values output by data-binding expressions. Before we look at ways to accomplish this, though, it is important that you have a thorough understanding of the type and value of data-binding expressions.

The Type and Value of a Data-Binding Expression

Every expression in any programming language has a type and a value. For example, the expression 4+5 is of type integer and has a value of 9. One of the things a compiler does is determine the type of expressions to ensure type safety. For example, a function that accepts an integer parameter could be called as

 MyFunction(4+5) 

because the expression 4+5 has the type integer.

Not surprisingly, data-binding expressions have a type and a value associated with them as well. In Listing 3.2, line 17, the data-binding expression

 <%# DataBinder.Eval(Container.DataItem, "au_fname") %> 

has a type of string, because the field au_fname in the authors table is a varchar(20). The value of the data binding expression depends on the value of Container.DataItem, which is constantly changing as the DataSource is being enumerated over. Hence, for the first row produced, the data-binding expression has a value of Johnson; the next row has a value of Marjorie; and so on. (See Figure 3.2 for a screenshot of Listing 3.2.)

When the Type of an Expression Is Known: Compile-Time Versus Runtime

The type of an expression is most commonly known at compile-time. If you have a type error, such as trying to assign a string to an integer, you will get a compile-time error. Being able to detect errors at compile-time has its advantages when it comes to debugging it's much easier to fix a problem you find when trying to compile the program than it is to fix a problem you can't find until you actually run the program.

Data binding expressions, however, have their type determined at runtime. This is because it would be impossible to determine the type at compile-time, because there's no way the compiler can determine the type structure of the DataSource, let alone the type that the DataBinder.Eval() method will return.

What Type Should Be Returned by a Data-Binding Expression?

Just like other expressions, the type that should be returned by the data-binding syntax depends upon where the data-binding expression is used. If it is used in a template to emit HTML, then a string type should be returned. Because all types support the ToString() method, literally any type can be accepted by a data-binding syntax that is to emit HTML in a template.

NOTE

There are data-binding situations that we've yet to examine in which the data-binding expression needs to be a complex data type.


Determining the Type of a Data-Binding Expression

Determining the type of a data-binding expression is fairly straightforward. Recall that the Container.DataItem has the type of whatever object the DataSource is enumerating over. Hence, if the DataSource is an integer array, the integers are being enumerated over, so the type of Container.DataItem is integer.

For complex objects like the DataSet and DataReader, determining what type of object being enumerated over can be a bit more work. The simplest way, in my opinion, is to just create a simple ASP.NET Web page that uses a DataList with an ItemTemplate. Inside the ItemTemplate, simply place <%# Container.DataItem %> (see Listing 3.6, line 27). When emitted as HTML, the Container.DataItem's ToString() method will be called, which will have the effect of displaying the Container.DataItem's namespace and class name. Listing 3.6 shows a simple DataGrid example that illustrates this point.

Listing 3.6 To Determine the Type of Container.DataItem, Simply Add <%# Container.DataItem %> to the ItemTemplate

[View full width]

  1: <%@ import Namespace="System.Data" %>   2: <%@ import Namespace="System.Data.SqlClient" %>   3: <script runat="server" language="VB">   4:   5:   Sub Page_Load(sender as Object, e as EventArgs)   6:     '1. Create a connection   7:      Const strConnString as String = "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:     objConn.Open()  'Open the connection  15:  16:     'Finally, specify the DataSource and call DataBind()  17:     dlDataItemTypeTest.DataSource = objCmd.ExecuteReader(CommandBehavior.   graphics/ccc.gifCloseConnection)  18:     dlDataItemTypeTest.DataBind()  19:  20:     objConn.Close()  'Close the connection  21:   End Sub  22:  23: </script>  24:  25: <asp:datalist  runat="server">  26:  <ItemTemplate>  27:   <%# Container.DataItem %>  28:  </ItemTemplate>  29: </asp:datalist> 

Figure 3.8 shows the output of Listing 3.6 when viewed through a browser. Note that the type is System.Data.Common.DbDataRecord.

Figure 3.8. The type of Container.DataItem is displayed on the page.

graphics/03fig08.gif

Building on the type of Container.DataItem, we can determine the type returned by DataBinder.Eval(). For example, if line 27 in Listing 3.6 was changed to

 <%# DataBinder.Eval(Container.DataItem, "au_fname") %> 

the type returned by the data binding expression would be the type of the au_fname field represented by the current DbDataRecord object. Because au_fname is of type varchar(20), the type of <%# DataBinder.Eval(Container.DataItem, "au_fname") %> is string.

Using Built-In Methods and Custom Functions in Data-Binding Syntax

At this point, we've examined the type issues involving data-binding syntax, and how to determine the type of a data-binding expression. Furthermore, we discussed what the type of a data-binding expression should be when it is in a template for the purpose of emitting HTML (type string).

Now that you have a solid understanding of typing and the data-binding syntax, we can look at using both built-in methods and custom functions to further enhance the output generated by data-binding expressions.

NOTE

By built-in methods I am referring to methods available in the .NET Framework classes, such as String.Format() or Regex.Replace(); recall that in Chapter 2's Listing 2.5 we saw an example of using the String.Format() method call in a data-binding syntax setting (line 17). By custom functions, I am referring to functions that you write and include in your ASP.NET page's server-side script block or code-behind class.


A built-in method or custom function can be used in a data-binding expression like so:

 <%# FunctionName(argument1, argument2, ..., argumentN) %> 

More likely than not, the argument(s) to the function will involve the Container.DataItem object, most likely in a DataBinder.Eval() method call. The function FunctionName should return a string (the HTML to be emitted) and accept parameters of the appropriate type.

To help clarify things, let's look at a simple example. Imagine that we are displaying sales information about the various books in the pubs database, as we did in Listing 3.4. As you'll recall, Listing 3.4 displayed a list of each book along with the book's year-to-date sales and price. Perhaps we'd like to customize our output so that books that have sold more than 10,000 copies have their sales data highlighted. Listing 3.7 contains the code for an ASP.NET Web page that provides such functionality.

Before you delve into the code in any great detail, first take a look at the screenshot of Listing 3.7, shown in Figure 3.9. Note that those books that have sold more than 10,000 copies have their sales figure highlighted.

Figure 3.9. Books with more than 10,000 sales have their sales figure highlighted.

graphics/03fig09.gif

Listing 3.7 Books with Sales Greater Than 10,000 Copies Are Highlighted
  1: <%@ import Namespace="System.Data" %>   2: <%@ import Namespace="System.Data.SqlClient" %>   3: <script runat="server" language="C#">   4:   5:   void Page_Load(Object sender, EventArgs e)   6:   {   7:    // 1. Create a connection   8:    const string strConnString = "server=localhost;uid=sa;pwd=;database=pubs";   9:    SqlConnection objConn = new SqlConnection(strConnString);  10:  11:    // 2. Create a command object for the query  12:    const string strSQL = "SELECT * FROM titles WHERE NOT ytd_sales IS NULL";  13:    SqlCommand objCmd = new SqlCommand(strSQL, objConn);  14:  15:    objConn.Open();  // Open the connection  16:  17:    //F inally, specify the DataSource and call DataBind()  18:    dgTitles.DataSource = objCmd.ExecuteReader(CommandBehavior. CloseConnection);  19:    dgTitles.DataBind();  20:  21:    objConn.Close();  // Close the connection  22:   }  23:   24:   string Highlight(int ytdSales)  25:   {  26:    if (ytdSales > 10000)  27:    {  28:     return "<span style=\"background-color:yellow;\">" +  29:          String.Format("{0:#,###}", ytdSales) + "</span>";  30:    }  31:    else  32:     return String.Format("{0:#,###}", ytdSales);  33:   }  34:  35: </script>  36: <asp:datagrid  runat="server"  37:    AutoGenerateColumns="False"  38:    Font-Name="Verdana" Width="50%"  39:    HorizontalAlign="Center" ItemStyle-Font-Size="9">  40:  41:  <HeaderStyle BackColor="Navy" ForeColor="White"  42:     HorizontalAlign="Center" Font-Bold="True" />  43:  44:  <AlternatingItemStyle BackColor="#dddddd" />  45:  46:  <Columns>  47:   <asp:BoundColumn DataField="title" HeaderText="Title"  48:            ItemStyle-Width="70%" />  49:  50:   <asp:TemplateColumn HeaderText="Copies Sold"  51:      ItemStyle-HorizontalAlign="Right"  52:      ItemStyle-Wrap="False">  53:    <ItemTemplate>  54:      <b><%# Highlight((int) DataBinder.Eval(Container.DataItem, "ytd_sales")) %></b>  55:    </ItemTemplate>  56:   </asp:TemplateColumn>  57:  </Columns>  58: </asp:datagrid> 

In examining the code in Listing 3.7, first note that the SQL string (line 12) has a WHERE clause that retrieves only books whose ytd_sales field is not NULL. The titles database table is set up so that the ytd_sales field allows NULL, representing a book with no sales. Because accepting NULLs slightly complicates our custom function, I've decided to omit books whose ytd_sales field contains NULLs we'll look at how to handle NULLs shortly.

Next, take a look at the Highlight() function (lines 24 33). The function is rather simple, taking in a single parameter (an int) and returning a string. The function simply checks whether the input parameter, ytdSales, is greater than 10,000 if it is, a string is returned that contains a span HTML tag with its background-color style attribute set to yellow; the value of ytdSales, formatted using String.Format() to include commas every three digits; and a closing span tag (lines 28 and 29). If ytdSales is not greater than 10,000, the value of ytdSales is returned, formatted to contain commas every three digits (line 22).

Finally, check out the ItemTemplate (line 54) in the TemplateColumn control. Here we call the Highlight() function, passing in a single argument: DataBinder. Eval(Container.DataItem, "ytd_sales"). At first glance, you might think that the type returned by DataBinder.Eval() here is type integer, because ytd_sales is an integer field in the pubs database. This is only half-correct. While the DataBinder. Eval() call is returning an integer, the compiler is expecting a return value of type Object. (Realize that all types are derived from the base Object type.) Because C# is type-strict, we must cast the return value of the DataBinder.Eval() method to an int, which is the data type expected by the Highlight() function. (Note that if you are using Visual Basic .NET, you do not need to provide such casting unless you specify strict casting via the Strict="True" attribute in the @Page directive; for more information on type strictness, see the resources in the "On the Web" section.)

Handling NULL Database Values

The custom function in Listing 3.7 accepts an integer as its input parameter. If the database field being passed into the custom function can return a NULL (type DBNull), then a runtime error can result when a NULL value is attempted to be cast into an int.

NOTE

NULL values in database systems represent unknown data. For example, imagine that you had a database table of employees, and one of the table fields was BirthDate, which stored the employee's date of birth. If for some reason you did not have the date of birth information for a particular employee, you could store the value NULL for that employee's BirthDate field. It is important to note that NULL values should not be used to represent zero, since any expression involving a NULL field results in a NULL value.


To handle NULLs, we'll adjust the Highlight() function to accept inputs of type Object, thus allowing any class to be passed in (because all classes are derived, directly or indirectly, from the Object class). Then, in the Highlight() function we'll check to see whether the passed-in value is indeed a NULL. If it is, we can output some message like, "No sales yet reported." If it is not NULL, we'll simply cast it to an int and use the code we already have to determine whether it should be highlighted. Listing 3.8 contains the changes needed for Listing 3.7 to accept NULLs:

Listing 3.8 The Highlight Function Has Been Adjusted to Accept NULLs
  1: <%@ Page Language="c#" %>   2: <%@ import Namespace="System.Data" %>   3: <%@ import Namespace="System.Data.SqlClient" %>   4: <script runat="server">   5:   6:   void Page_Load(Object sender, EventArgs e)   7:   {   8:    // 1. Create a connection   9:    const string strConnString = "server=localhost;uid=sa;pwd=;database=pubs";  10:    SqlConnection objConn = new SqlConnection(strConnString);  11:  12:    // 2. Create a command object for the query  13:    const string strSQL = "SELECT * FROM titles";  14:    SqlCommand objCmd = new SqlCommand(strSQL, objConn);  15:  16:    objConn.Open();  // Open the connection  17:  18:    //F inally, specify the DataSource and call DataBind()  19:    dgTitles.DataSource = objCmd.ExecuteReader(CommandBehavior. CloseConnection);  20:    dgTitles.DataBind();  21:  22:    objConn.Close();  // Close the connection  23:   }  24:  25:   string Highlight(object ytdSales)  26:   {  27:    if (ytdSales.Equals(DBNull.Value))  28:    {  29:     return "<i>No sales yet reported...</i>";  30:    }  31:    else  32:    {  33:     if (((int) ytdSales) > 10000)  34:     {  35:      return "<span style=\"background-color:yellow;\">" +   36:          String.Format("{0:#,###}", ytdSales) + "</span>";  37:     }  38:     else  39:     {  40:      return String.Format("{0:#,###}", ytdSales);  41:     }  42:    }  43:   }  44:  45: </script>  46:  47: <asp:datagrid  runat="server"  48:  49:  ... some DataGrid markup removed for brevity ...  50:  51:   <asp:TemplateColumn HeaderText="Copies Sold"  52:      ItemStyle-HorizontalAlign="Right"  53:      ItemStyle-Wrap="False">  54:    <ItemTemplate>  55:      <b><%# Highlight(DataBinder.Eval(Container.DataItem, "ytd_sales")) %></b>  56:    </ItemTemplate>  57:   </asp:TemplateColumn>  58:  </Columns>  59: </asp:datagrid> 

Listing 3.8 contains a few changes. The two subtle changes occur on lines 13 and 55. On line 13, the SQL query is altered so that all rows from the titles table are returned, not just those that are not NULL. On line 55, the cast to int was removed, because the DataBinder.Eval() function might return NULLs as well as integers.

The more dramatic change occurs in the Highlight function (lines 25 43). In Listing 3.8, Highlight() accepts an input parameter of type Object; this allows for any type to be passed into the function (of course, we only expect types of integers or DBNull to be passed in). On line 27, a check is made to determine whether the ytdSales parameter is of type DBNull (the DBNull.Value property is a static property of the DBNull class that returns an instance of the DBNull class the Equals method determines whether two objects are equal). If ytdSales represents a NULL database value, the string "No sales yet reported" is returned on line 29. Otherwise, ytdSales is cast to an int and checked to see whether it is greater than 10,000. The remaining lines of Highlight() are identical to the code from Highlight in Listing 3.7.

Figure 3.10 shows a screenshot from the code in Listing 3.8. Note that those rows that have NULL values for their ytd_sales field have No sales yet reported… listed under the Copies Sold column.

Figure 3.10. Database columns that have a NULL value have a helpful message displayed.

graphics/03fig10.gif

A Closing Word on Using Custom Functions in Templates

As we have seen, using customized functions in a data-binding setting allows for the data-bound output to be altered based upon the value of the data itself. For example, if you were displaying profit and loss information in a data Web control, you might opt to use such custom functions to have negative profits appear in red.

The last two examples showed the use of simple custom functions that accept one parameter. Of course, there is no reason why you couldn't pass in more than one parameter. Perhaps you want to pass in two database field values and then output something based on the two values.

Another neat thing you can do with these custom functions is add information to your data Web controls that might not exist in the database. For example, from the titles table, we have both a ytd_sales field and a price field. Imagine that we want to display the book's total revenues this would be simply the sales multiplied by the price.

Listing 3.9 shows a quick example of how to accomplish this. Essentially, all we have to do is pass both the ytd_sales and price fields to our custom function, multiply them, and then return the value.

Listing 3.9 Custom Functions Can Include Multiple Input Parameters

[View full width]

  1: <%@ import Namespace="System.Data" %>   2: <%@ import Namespace="System.Data.SqlClient" %>   3: <script runat="server" language="VB">   4:   5:   Sub Page_Load(sender as Object, e as EventArgs)   6:    '1. Create a connection   7:    Const strConnString as String = "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 titles WHERE NOT ytd_sales IS NULL"  12:    Dim objCmd as New SqlCommand(strSQL, objConn)  13:  14:    objConn.Open()  'Open the connection  15:  16:    'Finally, specify the DataSource and call DataBind()  17:    dgTitles.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection)  18:    dgTitles.DataBind()  19:  20:    objConn.Close()  'Close the connection  21:   End Sub  22:  23:  24:   Function CalcRevenues(sales as Integer, price as Single)  25:    Return String.Format("{0:c}", sales * price)  26:   End Function  27:  28: </script>  29: <asp:datagrid  runat="server"  30:  31:  ... some DataGrid markup removed for brevity ...  32:  33:   <asp:TemplateColumn HeaderText="Revenues"  34:      ItemStyle-HorizontalAlign="Right"  35:      ItemStyle-Wrap="False">  36:    <ItemTemplate>  37:      <b><%# CalcRevenues(DataBinder.Eval(Container.DataItem, "ytd_sales"), DataBinder. graphics/ccc.gifEval(Container.DataItem, "price")) %></b>  38:    </ItemTemplate>  39:   </asp:TemplateColumn>  40:  </Columns>  41: </asp:datagrid> 

Note that here, as with Listing 3.7, our SQL query only grabs those rows whose ytd_sales field is not NULL (line 11). My motivation behind this was to keep the CalcRevenues() custom function as clean as possible; you are encouraged to adjust the code in Listing 3.9 to allow for NULLs.

The custom function, CalcRevenues(), calculates the total revenues for each book. It accepts two input parameters (sales and price, an integer and single, respectively), and then multiplies them, using the String.Format() method to format the result into a currency. The string returned by the String.Format() method is then returned as the data-binding expression's value and is emitted as HTML.

Line 37 contains the call to CalcRevenues() in the data-binding syntax. Note that two database values are passed into CalcRevenues() the ytd_sales field value and the price field value.

Figure 3.11 contains a screenshot of the code in Listing 3.9 when viewed through a browser.

Figure 3.11. The total revenue for each book is shown.

graphics/03fig11.gif

In closing, realize that the amount of customization you can do using the data-binding syntax is virtually limitless.



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