Pertama kita harus cek dulu kolom mana yang akan di custom. Kemudian tentukan juga kriteria yang sudah ditentukan untuk cell tersebut, misalnya kalau cell tersebut di select oleh user maka custom cell painting yang kita buat akan tetap tampilannya seperti yang sudah dibuat. Satu hal yang perlu dilakukan yaitu set properti Handled = True dari parameter DataGridViewCellPaintingEventArgs. Properti tersebut digunakan untuk memberitahukan pada datagridview bahwa kita akan tetap merender cell tersebut sesuai dengan yang diinginkan. Kalau setting properti tersebut lupa dilakukan maka custom cell paintingnya ga akan di render.
Untuk membuat LinearGradientBrush nya kita perlu Import terlebih dahulu namespace nya. Setelah itu kita buat rectangle nya dengan batas CellBound dari cell yang aktif, dan juga location yang kita buat berdasarkan koordinat x dan y dari cell tersebut. Finally, we render again the value of the current cell by calling DrawString method from the Graphics property from its active cell. Ok...see the complete code and the result screen shot :
1: Option Strict On
2:
3: Imports ADONetHelper
4: Imports System.Data.SqlClient
5: Imports System.Drawing.Drawing2D
6:
7: Public Class frmCellPainting
8:
9: Private strConn As String = My.Settings.connString
10: Private sqlConn As New SqlConnection(strConn)
11: Private rowToPaint As DataGridViewRow
12:
13: Private Sub LoadData()
14: Dim dtProd As DataTable = _
15: ADONetHelper.DataTableObject.GetDataTableFromDataReader( _
16: "Select * From Products", CommandType.Text, sqlConn, _
17: "products")
18:
19: Me.DataGridView1.DataSource = dtProd
20: Me.DataGridView1.Columns(0).Frozen = True
21: End Sub
22:
23: Private Sub Button1_Click(ByVal sender As System.Object, _
24: ByVal e As System.EventArgs) Handles Button1.Click
25: Me.LoadData()
26: End Sub
27:
28: Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
29: ByVal e As _
30: System.Windows.Forms.DataGridViewCellPaintingEventArgs) _
31: Handles DataGridView1.CellPainting
32:
33: If e.ColumnIndex = 6 And e.RowIndex >= 0 Then
34: If (e.State <> DataGridViewElementStates.Selected) Then
35: rowToPaint = Me.DataGridView1.Rows(e.RowIndex)
36:
37: If Not rowToPaint.IsNewRow AndAlso CInt(e.Value) = 0 _
38: Then '//jika stok = 0
39: e.Handled = True
40:
41: Dim rect As New Rectangle(e.CellBounds.X, _
42: e.CellBounds.Y, e.CellBounds.Width - 1, _
43: e.CellBounds.Height - 1)
44:
45: Dim linBrush As New LinearGradientBrush( _
46: rect, Color.Yellow, Color.GreenYellow, _
47: LinearGradientMode.Horizontal, True)
48:
49: Dim myFont As New Font("Tahoma", 10, _
50: FontStyle.Italic Or FontStyle.Bold)
51:
52: e.Graphics.DrawRectangle(New Pen(Color.Black, 2), _
53: rect)
54:
55: e.Graphics.FillRectangle(linBrush, rect)
56:
57: e.Graphics.DrawString(e.FormattedValue.ToString _
58: & "-Warning!", myFont, New SolidBrush(Color.Red), _
59: rect)
60: End If
61: End If
62: End If
63: End Sub
64:
65: End Class