Click here to Skip to main content
Click here to Skip to main content

Customize DataGridView row without iteration

By , 18 May 2011
Rate this:
Please Sign up or sign in to vote.
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#
   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
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)

About the Author

ambarishtv
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

 
Questionwhat about the post paint method Pinmemberrabosa20-Mar-12 6:16 
GeneralReason for my vote of 2 It's too simple for codeproject arti... PinmemberAgah Burak DEMİRKAN23-Jun-11 3:39 
GeneralRe: Thank you Pinmemberambarishtv23-Jun-11 3:54 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 18 May 2011
Article Copyright 2011 by ambarishtv
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid