Changing BackColor of Each Cell of a GridView

Posted on July 1st, 2008.

This article is about formatting the cells of a gridview. Imagine you have to change backcolor of a paticular cell in the grid view  conditionally. How would you do it? Below is the Solution for this.

Suppose you have to compare the value of a paticular cell with date field which comes from the database. Lets keep the date field in a variablesi,e.
CDateVariable = CDate(ds.Tables(1).Rows(0)(“DateFromDatabase”))

Keep the value in  the cell that u want to compare in a label control. Then check for the control in  the code behind in this way:
If e.Row.RowType = DataControlRowType.DataRow Then
Now Define a label variable in code behind
Dim lbl As Label
Now by using findcontrol attribute, assign the value of the label control in the cell to the variable ‘ lbl ‘ .
lbl =
CType(e.Row.Cells(10).FindControl(“lblLastCorpReview”), Label)
Check wether the value in the label control is blank or not.
If lbl.Text <> “” Then
After that as we are comparing the date variable change the data type of the value in the label control to date in this fashion:
tLastCorpReview = CDate(lbl.Text)
Now compare the date ( or any condition you want):
If (DateTime.Compare(tLastCorpReview, DateFromDatabase)) < 0 Then
If the condition is true ( or false accordin to your bussiness logic) change the color of the cell using line below:(‘ changing the color of 10th cell of each row
)
e.Row.Cells(10).BackColor = System.Drawing.ColorTranslator.FromHtml(“#FFFFE6″)
End If
End If
End If

Now the  total codes will be :

If
e.Row.RowType = DataControlRowType.DataRow Then
Dim lbl As Label
lbl =
CType(e.Row.Cells(10).FindControl(“lblDateFromDatabase”
), Label)

If lbl.Text <> “” Then
celldate= CDate(lbl.Text)
If (DateTime.Compare(celldate, CDateVariable)) < 0 Then
e.Row.Cells(10).BackColor = System.Drawing.ColorTranslator.FromHtml(“#FFFFE6″)
End If
End If
End If


Make a Comment

Make A Comment: ( 1 so far )

blockquote and a tags work here.

One Response to “Changing BackColor of Each Cell of a GridView”

RSS Feed for Dreams will remain dreams until you stop dreaming and start working Comments RSS Feed

It seems remarkable phrase to me is

Каталог статей
January 26th, 2010

Where's The Comment Form?

About

Sharing my xperiences

RSS

Subscribe Via RSS

  • Subscribe with Bloglines
  • Add your feed to Newsburst from CNET News.com
  • Subscribe in Google Reader
  • Add to My Yahoo!
  • Subscribe in NewsGator Online
  • The latest comments to all posts in RSS
  • Subscribe in Rojo

Meta

Liked it here?
Why not try sites on the blogroll...