我在更改DataGridView cells
的前景色時遇到問題。我有多個運行產生DataGridView
,我使用下面的代碼:你如何改變Forecolor?
For Each tbp As TabPage In frmTimingP2P.tabctrlTimingTable.TabPages
For Each ctrl As Control In tbp.Controls
Dim dgv As DataGridView = TryCast(ctrl, DataGridView)
If Not dgv Is Nothing Then
For Each dc As DataGridViewColumn In dgv.Columns
If dc.Name.EndsWith("Gain/Loss") Then
For Each dr As DataGridViewRow In dgv.Rows
If Not dr.Cells(dc.Index).Value Is DBNull.Value Then
If dr.Cells(dc.Index).Value = 0 Then
dr.Cells(dc.Index).Style.ForeColor = Color.Blue
ElseIf dr.Cells(dc.Index).Value < 0 Then
dr.Cells(dc.Index).Style.ForeColor = Color.Red
ElseIf dr.Cells(dc.Index).Value > 0 Then
dr.Cells(dc.Index).Style.ForeColor = Color.Green
End If
End If
Next
End If
Next
dgv.Refresh()
End If
Next
Next
此代碼工作正常只在當前焦點的DataGridView,但不是在別人DataGridview
。
我已經修改了我的代碼,現在已拿出了以下內容:
Private Sub dgvOverview_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvOverview.CellFormatting
Dim dgv As New DataGridView
dgv = sender
If dgv.Columns(e.ColumnIndex).Name.EndsWith("Gain/Loss") Then
If e.Value IsNot DBNull.Value Then
Dim intCellValue As Integer = CType(e.Value, Integer)
If intCellValue = 0 Then
e.CellStyle.ForeColor = Color.Blue
ElseIf intCellValue > 0 Then
e.CellStyle.ForeColor = Color.Green
ElseIf intCellValue < 0 Then
e.CellStyle.ForeColor = Color.Red
End If
End If
End If
End Sub
這一切運作良好。謝謝您的幫助!
這確實爲我工作,但我有另外一個問題。我修改了上面的代碼。 – J2Tuner
其實這段代碼工作完美。謝謝! – J2Tuner