在ItemTemplate中格式化UnitsInStockLabel Label


  本文标签:ItemTemplate

  最后一步就是要在ItemTemplate中设置UnitsInStockLabel的样式为红色字体,在ItemTempelete中查找控件可以使用FindControl(“controlID”)方法

  1. WebControlType someName = (WebControlType)FormViewID.FindControl("controlID"); 

  对于我们这个例子我们可以用如下代码来查找该Label控件

  1. Label unitsInStock = (Label)LowStockedProductsInRed.FindControl("UnitsInStockLabel"); 

  当我们找到这个控件时则可以修改其对应的style属性,在style.css中已经有一个写好的LowUnitsInStockEmphasis的cSS Class ,我们通过下面的代码将cSS Class设置到对应的属性   

  1. protected void LowStockedProductsInRed_DataBound(object sender, EventArgs e)  
  2.  
  3.     {  
  4.  
  5.         // Get the ProductsRow object from the DataItem property...  
  6.  
  7.         Northwind.ProductsRow product = (Northwind.ProductsRow)((System.Data.DataRowView)LowStockedProductsInRed.DataItem).Row;  
  8.  
  9.         if (!product.IsUnitsInStockNull() && product.UnitsInStock < = 10)  
  10.  
  11.         {  
  12.  
  13.             Label unitsInStock = (Label)LowStockedProductsInRed.FindControl("UnitsInStockLabel");  
  14.  
  15.    
  16.  
  17.             if (unitsInStock != null)  
  18.  
  19.             {  
  20.  
  21.                 unitsInStock.CssClass = "LowUnitsInStockEmphasis";  
  22.  
  23.             }  
  24.  
  25.         }  
  26.  
  27.     }  
  28.  

  注意: 这种方式在FormView和GridView中也可以通过设置TemplateFields来达到同样的效果,我们将在下一篇中讨论TemplateFields

  图7显示FormView在当UnitsInStock大于10的情况,图8则显示小于等于10的情况

  在高于10的情况下,没有值被格式化 

  ItemTemplate: 在高于10的情况下,没有值被格式化

  小于等于10时,值用红色字体显示 

  ItemTemplate:小于等于10时,值用红色字体显示

  用GridView的 RowDataBound 事件自定义格式化

  前面我们讨论了在FormView和DetailsView中实现数据绑定的步骤,现在让我们回顾下

  1.DataBinding事件触发

  2.数据绑定到数据绑定控件

  3.DataBound事件触发

  对于FormView和DetailsView有效因为只需要显示一个数据,而在GridView中,则要显示所有数据,相对于前面三个步骤,步骤二有些不同

  在步骤二中,GridView 列出所有的数据,对于某一个记录将创建一个GridViewRow 实例并绑定,对于每个添加到GridView 中的 GridViewRow两个事件将会触发:

  · RowCreated – 当GridViewRow被创建时触发

  ·RowDataBound – 当前记录绑定到GridViewRow时触发.

  对于GridView,请使用下面的步骤

  1.DataBinding事件触发

  2.数据绑定到数据绑定控件

  对于每一行数据..

  a. 创建GridViewRow

  b. 触发 RowCreated 事件

  c.绑定数据到GridViewRow

  d. 触发RowDataBound事件

  e. 添加GridViewRow到Rows 集合

  DataBound事件触发

  为了自定义格式化GridView单独记录,我们需要为RowDataBound事件创建事件处理,让我们添加一个GridView到CustomColors.aspx中,并显示name, category, 和 price,用黄色背景高亮那些价格小于$10.00的产品