Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Customize DataGridView row without iteration

Rate me:
Please Sign up or sign in to vote.
4.10/5 (10 votes)
18 May 2011CPOL 32.1K   12   4
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)


Written By
Software Developer
India India



Hi I' Ambarish from India. I've three and half year of experience in application
development solutions.
Educational Qualification MCA -  from KristuJyoti College of management and technology (MG
University)

B.Sc (Physics) - from NSS College, Changanacherry (MG University)
Skill Set C#,winforms,asp.net,MVC 3, Java,Design Patterns,VB, Android,JQuery Mobile,SQL,MySqlUML.



Comments and Discussions

 
Questionimproving row alternating Pin
rom32327-Jan-16 15:58
rom32327-Jan-16 15:58 
Questionwhat about the post paint method Pin
rabosa20-Mar-12 6:16
professionalrabosa20-Mar-12 6:16 
GeneralReason for my vote of 2 It's too simple for codeproject arti... Pin
Agah Burak DEMİRKAN23-Jun-11 3:39
Agah Burak DEMİRKAN23-Jun-11 3:39 
GeneralRe: Thank you Pin
ambarishtv23-Jun-11 3:54
ambarishtv23-Jun-11 3:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.