在RowDataBound的事件處理中編碼確定數(shù)據(jù)對應(yīng)的值
當(dāng)ProductsDataTable綁定到GridView,GridView將會產(chǎn)生若干個ProductsRow。GridViewRow的DataItem屬性將會生成一個實際的ProductRow。在GridView的 RowDataBound事件發(fā)生之后,為了確定UnitsInStock的值,我們需要創(chuàng)建RowDataBound的事件處理,在其中我們可以確定UnitsInStock的值并做相應(yīng)的格式化
EventHandler的創(chuàng)建過程和前面兩個一樣
RowDataBound: 創(chuàng)建GridView的RowDataBound事件的事件處理
在后臺代碼里將會自動生成如下代碼
- protected void HighlightCheapProducts_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- }
當(dāng)RowDataBound事件觸發(fā),第二個參數(shù)GridViewRowEventArgs中包含了對GridViewRow的引用,我們用如下的代碼來訪問GridViewRow中的ProductsRow
- protected void HighlightCheapProducts_RowDataBound(object sender, GridViewRowEventArgs e)
- { // Get the ProductsRow object from the DataItem property...
- Northwind.ProductsRow product = (Northwind.ProductsRow)((System.Data.DataRowView)e.Row.DataItem).Row;
- if (!product.IsUnitPriceNull() && product.UnitPrice < 10m)
- {
- // TODO: Highlight the row yellow...
- }
- }
當(dāng)運(yùn)用RowDataBound事件處理時,GridView由各種類型不同的行組成,而事件發(fā)生針對所有的行類型, GridViewRow的類型可以由RowType屬性決定,可以是以下類型中的一種
·DataRow – GridView的DataSource中的一條記錄
·EmptyDataRow – GridView的DataSource顯示出來的某一行為空
·Footer – 底部行; 顯示由GridView的ShowFooter屬性決定
·Header – 頭部行; 顯示由GridView的ShowHeader屬性決定
·Pager – GridView的分頁,這一行顯示分頁的標(biāo)記
·Separator – 對于GridView不可用,但是對于DataList和Reapter的RowType屬性卻很有用,我們將在將來的文章中討論他們
當(dāng)上面四種(DataRow, Pager Rows Footer, Header)都不合適對應(yīng)值時,將返回一個空的數(shù)據(jù)項, 所以我們需要在代碼中檢查GridViewRow的RowType屬性來確定:
- protected void HighlightCheapProducts_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- // Make sure we are working with a DataRow
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- // Get the ProductsRow object from the DataItem property...
- Northwind.ProductsRow product = (Northwind.ProductsRow)((System.Data.DataRowView)e.Row.DataItem).Row;
- if (!product.IsUnitPriceNull() && product.UnitPrice < 10m)
- {
- // TODO: Highlight row yellow...
- }
- }
- }
【編輯推薦】