Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Customize DataGridView row without iteration

4.10/5 (10 votes)
18 May 2011CPOL 32.9K  
here I'm going to shows a helpfull tip. Suppose if I need to assign different colors for each row in the DataGridView, we usually do it iterating through codebehind. There is an alternative for this instance which is directly binded DataGridView rows based on certain conditions.

Advantage :
Avoid loop iteraion after loading

C#
C#
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
         DataGridView grd = sender as DataGridView;
         if (grd.Rows[e.RowIndex].Cells[1].Value.ToString() == "STOPED")
         {
             grd.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.HotPink;
         }
         if (grd.Rows[e.RowIndex].Cells[1].Value.ToString() == "ACTIVE")
         {
             grd.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGreen;
         }
}


VB.Net
VB
Private Sub dataGridView1_RowPrePaint(sender As Object, e As DataGridViewRowPrePaintEventArgs)
    Dim grd As DataGridView = TryCast(sender, DataGridView)
    If grd.Rows(e.RowIndex).Cells(1).Value.ToString() = "STOPED" Then
        grd.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.HotPink
    End If
    If grd.Rows(e.RowIndex).Cells(1).Value.ToString() = "ACTIVE" Then
        grd.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
    End If
End Sub

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)