其实这个问题网上老早就有了,在此只是整理了一下,可以使多个Cell变成不同的颜色。
Public Class DataGridColoredTextBoxColumn
Inherits DataGridTextBoxColumn
Private m_Row As Integer = -1
Private m_BackColor As Color = Color.White
Private m_ForeColor As Color = Color.Black
Sub New(ByVal Row As Integer, ByVal [ForeColor] As Color)
m_Row = Row
m_ForeColor = ForeColor
End Sub
Sub New(ByVal row As Integer, ByVal [ForeColor] As Color, ByVal [BackColor] As Color)
m_Row = row
m_ForeColor = ForeColor
m_BackColor = BackColor
End Sub
Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
ByVal bounds As Rectangle, ByVal source As CurrencyManager, _
ByVal rowNum As Integer, ByVal backBrush As Brush, _
ByVal foreBrush As Brush, ByVal alignToRight As Boolean)
Try
If m_Row <> -1 Then
If rowNum = m_Row Then
backBrush = New SolidBrush(m_BackColor)
foreBrush = New SolidBrush(m_ForeColor)
End If
End If
Catch ex As Exception
' empty catch
Finally
MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
End Try
End Sub
End Class
调用代码:
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ada As New OleDbDataAdapter("select * from class_info", _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= f:/StudentDB.mdb")
Dim mytable As New DataTable
ada.Fill(mytable)
Dim mGridStyle As New DataGridTableStyle
mGridStyle.MappingName = mytable.TableName
Dim mColumnStyle As DataGridColumnStyle
Dim column As Integer = 0
For Each c As DataColumn In mytable.Columns
If column = 1 Then 'Cell(0,1)变为红色
mColumnStyle = New DataGridColoredTextBoxColumn(0, Color.Red)
ElseIf column = 2 Then 'Cell(1,2)变为蓝色
mColumnStyle = New DataGridColoredTextBoxColumn(1, Color.Blue)
Else '其它不变
mColumnStyle = New DataGridTextBoxColumn
End If
With mColumnStyle
.MappingName = c.ColumnName
.HeaderText = c.ColumnName
End With
mGridStyle.GridColumnStyles.Add(mColumnStyle)
column += 1
Next
DataGrid1.TableStyles.Add(mGridStyle)
DataGrid1.DataSource = mytable
End Sub
End Class