Change Cell Color

Okay here’s just a little code snippet that I’ve done today to change the cell colors by validating the Numberic values if it’s a signed value it get’s the color rad otherwise green you can modify it how ever you want it to be.

For Visual Basic
Private Sub ChangeCellFontColor(ByVal DataGridView As DataGridView, ByVal ColumnName As String)
        Dim Index As Integer = 0
        If Not (DataGridView.Rows.Count) = 0 Then
            If Not (String.IsNullOrEmpty(ColumnName)) Then
                For Index = 0 To DataGridView.Rows.Count - 1
                    If IsNumeric((DataGridView.Rows(Index).Cells(ColumnName).Value)) Then
                        If DataGridView.Rows(Index).Cells(ColumnName).Value < 0 Then
                            DataGridView.Rows(Index).Cells(ColumnName).Style.ForeColor = Color.Red
                        Else
                            DataGridView.Rows(Index).Cells(ColumnName).Style.ForeColor = Color.Green
                        End If
                    End If
                Next
            End If
        End If
    End Sub
For CSharp
private void ChangeCellFontColor(DataGridView DataGridView, string ColumnName)
{
	int Index = 0;
	if (!((DataGridView.Rows.Count) == 0)) {
		if (!(string.IsNullOrEmpty(ColumnName))) {
			for (Index = 0; Index <= DataGridView.Rows.Count - 1; Index++) {
				if (Information.IsNumeric((DataGridView.Rows(Index).Cells(ColumnName).Value))) {
					if (DataGridView.Rows(Index).Cells(ColumnName).Value < 0) {
						DataGridView.Rows(Index).Cells(ColumnName).Style.ForeColor = Color.Red;
					} else {
						DataGridView.Rows(Index).Cells(ColumnName).Style.ForeColor = Color.Green;
					}
				}
			}
		}
	}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s