Chapter 11. Altering the Data Before It's RenderedIN THIS CHAPTER
One of the many advantages of the data Web controls is how easy they make it to display data on an ASP.NET Web page. If you want to display information from a database with perhaps some stylistic HTML added, only a measly two lines of code are needed: setting the data Web control's DataSource property to an applicable object, and then calling the DataBind() method. This simple approach lends itself well to displaying data from a data store "as is." But what if you want to display data differently, depending on the value of the data itself? In previous chapters, we examined two ways to accomplish this. One method is to write a custom function that accepts a value from one or more of the DataSource's fields as input and returns a string. This function would then be called using the data-binding syntax: <%# YourFunction(DataBinder.Eval(Container.DataItem, "FieldName")) %> We first examined how to use this approach in Chapter 3, "Customizing the HTML Output." This approach can be used in any of the data Web controls, but recall that data-binding syntax can only be employed in a DataGrid TemplateColumn column. The second approach is to provide event handlers for either the ItemCreated or ItemDataBound events, both of which are common to all three data Web controls. The ItemCreated and ItemDataBound events occur when the data Web control is being constructed. Specifically, the ItemCreated event fires when a new item (a DataGridItem, DataListItem, or RepeaterItem) is created for the data Web control, while the ItemDataBound event is raised when the current row in the DataSource is bound to the data Web control item. We first examined these events in Chapter 4, "Adding Buttons and Hyperlinks to the DataGrid Web Control." In this chapter, we will use both of these techniques to alter the data prior to displaying it, as well as examine scenarios in which one would be interested in altering the HTML output based on the value of the data. Although this chapter examines material covered in previous chapters, it looks at the material in greater depth, and in various real-world scenarios where these techniques might be used. |