如何在DataBound事件中編碼確定數(shù)據(jù)的值
為了將那些UnitPrice高于$75.00的產(chǎn)品用粗體,italic字體顯示出來,我們首先需要編碼確定UnitPrice的值,對(duì)于DetailsView我們可以通過DataBound事件完成. 我們選擇DetailsView并查看屬性視圖(F4位快捷鍵), 如果沒有顯示,則選擇 View(視圖)
Property Window(屬性窗口), 在確保您選擇了DetailsView的情況下雙擊DataBound事件或者輸入您要?jiǎng)?chuàng)建的事件名
DataBound: 為DataBound事件創(chuàng)建一個(gè)事件處理
代碼中將會(huì)自動(dòng)生成以下代碼
- protected void ExpensiveProductsPriceInBoldItalic_DataBound(object sender, EventArgs e)
- {
- }
我們可以通過DataItem屬性來設(shè)置DetailsView的綁定項(xiàng)(一些強(qiáng)類型的數(shù)據(jù)行(DataRow)組成的強(qiáng)類型的數(shù)據(jù)表(DataTable)), 當(dāng)數(shù)據(jù)表(DataTable)綁定到DetailsView時(shí),數(shù)據(jù)表的***行將被自動(dòng)綁定到DetailsView的DataItem屬性,而DataItem屬性中包含有DataRowView (Object類型),我們可以通過DataRowView來訪問一個(gè)ProductsRow 的DataRow實(shí)例,還可以檢測(cè)Object的值來確定ProductsRow實(shí)例是否存在
下面的代碼描述如何確定UnitPrice是否綁定到DetailsView并且高于$75.00
- protected void ExpensiveProductsPriceInBoldItalic_DataBound(object sender, EventArgs e)
- {
- // Get the ProductsRow object from the DataItem property...
- Northwind.ProductsRow product = (Northwind.ProductsRow)((System.Data.DataRowView) ExpensiveProductsPriceInBoldItalic.DataItem).Row;
- if (!product.IsUnitPriceNull() && product.UnitPrice > 75m)
- {
- // TODO: Make the UnitPrice text bold and italic
- }
- }
注意: 當(dāng)UnitPrice在數(shù)據(jù)庫的值為空,我們?cè)诮壎ǖ絇roductsRow’s UnitPrice屬性之前檢查確定他是否為空,這很重要因?yàn)槲覀兛梢酝ㄟ^檢查這個(gè)屬性來拋出一個(gè)強(qiáng)類型的異常 StrongTypingException exception.
【編輯推薦】