在RowDataBound的事件处理中编码确定数据对应的值


  本文标签:RowDataBound

  当ProductsDataTable绑定到GridView,GridView将会产生若干个ProductsRow  。GridViewRow的DataItem属性将会生成一个实际的ProductRow  。在GridView的 RowDataBound事件发生之后,为了确定UnitsInStock的值,我们需要创建RowDataBound的事件处理,在其中我们可以确定UnitsInStock的值并做相应的格式化

  EventHandler的创建过程和前面两个一样

  创建GridView的RowDataBound事件的事件处理 

  RowDataBound: 创建GridView的RowDataBound事件的事件处理

  在后台代码里将会自动生成如下代码

  1. protected void HighlightCheapProducts_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.  
  3. {  
  4.  
  5. }  
  6.  

  当RowDataBound事件触发,第二个参数GridViewRowEventArgs中包含了对GridViewRow的引用,我们用如下的代码来访问GridViewRow中的ProductsRow   

  1. protected void HighlightCheapProducts_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.  
  3.     {        // Get the ProductsRow object from the DataItem property...  
  4.  
  5.         Northwind.ProductsRow product = (Northwind.ProductsRow)((System.Data.DataRowView)e.Row.DataItem).Row;  
  6.  
  7.         if (!product.IsUnitPriceNull() && product.UnitPrice <  10m)  
  8.  
  9.         {  
  10.  
  11.             // TODO: Highlight the row yellow...  
  12.  
  13.        }  
  14.  
  15.     }  
  16.  

  当运用RowDataBound事件处理时,GridView由各种类型不同的行组成,而事件发生针对所有的行类型, GridViewRow的类型可以由RowType属性决定,可以是以下类型中的一种

  ·DataRow – GridView的DataSource中的一条记录

  ·EmptyDataRow – GridView的DataSource显示出来的某一行为空

  ·Footer – 底部行; 显示由GridView的ShowFooter属性决定

  ·Header – 头部行; 显示由GridView的ShowHeader属性决定

  ·Pager – GridView的分页,这一行显示分页的标记

  ·Separator – 对于GridView不可用,但是对于DataList和Reapter的RowType属性却很有用,我们将在将来的文章中讨论他们

  当上面四种(DataRow, Pager Rows Footer, Header)都不合适对应值时,将返回一个空的数据项, 所以我们需要在代码中检查GridViewRow的RowType属性来确定:

  1. protected void HighlightCheapProducts_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.  
  3. {  
  4.  
  5.         // Make sure we are working with a DataRow  
  6.  
  7.         if (e.Row.RowType == DataControlRowType.DataRow)  
  8.  
  9.         {  
  10.  
  11.             // Get the ProductsRow object from the DataItem property...  
  12.  
  13.             Northwind.ProductsRow product = (Northwind.ProductsRow)((System.Data.DataRowView)e.Row.DataItem).Row;  
  14.  
  15.             if (!product.IsUnitPriceNull() && product.UnitPrice <  10m)  
  16.  
  17.             {  
  18.  
  19.                 // TODO: Highlight row yellow...  
  20.  
  21.             }  
  22.  
  23.         }  
  24.  
  25. }  
  26.