1

の前色を変更できません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

これはすべてうまくいきます。助けてくれてありがとう!

4

1 に答える 1

1

DataGridView の CellFormatting イベントを処理する方がはるかに優れた方法です。詳細については、 http://msdn.microsoft.com/cs-cz/library/system.windows.forms.datagridview.cellformatting.aspxを参照してください。

于 2013-01-11T22:07:13.917 に答える