2008年5月23日 星期五

DataGridView - Row的條件格式化

上一篇是針對儲存格的條件格式化, 這一篇是針對資料記錄, 例如, 檢查庫存量小於10時, 將整筆記錄以紅色顯示.
DataGridView在進行Row的繪制流程時會觸發兩個事件, 分別是RowPrePaint及RowPostPaint, 這裡是要在處理完Row的繪製動作之後, 再將每個儲存格背景色改為紅色, 所以是在RowPostPaint事件處理.

使用e.RowIndex取得DataGridViewRow物件,取出DataGridViewRow物件後, 經由DataBoundItem屬性取得該筆記錄,
然後判斷記錄欄位是否符合條件, 若符合條件, 修改該記錄的每個儲存格Style.BackColor屬性.

    Private Sub ProductsDataGridView_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles ProductsDataGridView.RowPostPaint
If e.RowIndex <= 0 Then
Return
End If
Dim row As DataRowView
row = CType(ProductsDataGridView.Rows(e.RowIndex).DataBoundItem, DataRowView)
If row("UnitsInStock") < 10 Then
For Each cell As DataGridViewCell In ProductsDataGridView.Rows(e.RowIndex).Cells
cell.Style.BackColor = Color.Red
Next
End If
End Sub


圖: 庫存量小於10, 整筆以紅色顯示.
01

沒有留言:

張貼留言