你如何改变Forecolor?

时间:2013-01-11 21:53:20

标签: vb.net datagridview

我无法更改DataGridView cells的前景色。我有多个运行时生成DataGridView,我使用以下代码:

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

这一切都运作良好。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

更好的方法是处理DataGridView CellFormatting事件。有关详细信息,请参阅http://msdn.microsoft.com/cs-cz/library/system.windows.forms.datagridview.cellformatting.aspx

答案 1 :(得分:0)

我为你做了一件小事......

 For i As Integer = 0 To Me.dataGridView1.RowCount - 1
If Me.dataGridView(3, i).Value = 0 Then
    Me.dataGridView(4, i).Style.BackColor = Color.Blue
End If
 Next