Background color a row in datagrid based on cell value, please help!

mhouston

New member
Joined
Jun 28, 2005
Messages
3
Programming Experience
Beginner
Hi all. I'm going crazy here, i've been going through every example i could get my hands on to background color a row or cell in my datagrid. i have inherited this code from a collegaue, and i have been able to update the page no problem, but then i wanted to do something which i thought was simple; color the background of the row, depending on the cells value. i know there are a good few samples out there, but i have tried to integrate each one into mine, and none work, i am totally spent trying to make it work.
i have a database with a certain column containing the status value. it can either be "OPEN", "CLOSED","SENT" etc. If the cell contains "OPEN", i want the row to be background colored red. simple as that. the code already exists to display the grid, it works great, but integrating this new code is killing me. i am using the 'code behind' approach. here are my files, recomm1.aspx, and recomm1.vb

I'm sorry i'm putting in all of the file text, but it is probably best in order to illustrate everything involved in this datagrid. I welcome any help. Thanks for your time.

recomm1.aspx
-----------------------

<%@ Page Language="VB" Debug="true" codebehind="recomm1.vb" Src="recomm1.vb" Inherits="SortingTemplateColumns" %>
<html>
<form runat="server">
<asp:DataGrid id="DataGrid1" runat="server" Width="100%" ForeColor="Black" GridLines="Vertical" CellPadding="3" BackColor="White" _
BorderColor="#999999" BorderWidth="1px" BorderStyle="Solid" AutoGenerateColumns="False" AllowSorting="True" AllowPaging="True" _
OnItemCommand="DataGrid1_CommandItem" OnItemDataBound="DataGrid1_ItemDataBound">
<FooterStyle backcolor="#CCCCCC"></FooterStyle>
<HeaderStyle font-names="Arial" font-bold="True" horizontalalign="Center" forecolor="White" backcolor="Black"></HeaderStyle>
<PagerStyle horizontalalign="Center" forecolor="Black" backcolor="#999999" mode="NumericPages"></PagerStyle>
<SelectedItemStyle font-bold="True" forecolor="White" backcolor="#000099"></SelectedItemStyle>

<Columns>
<asp:TemplateColumn>
<HeaderStyle width="10%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton2" runat="server" forecolor="white" CommandName="sort" CommandArgument="Date">Date</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblDate" text= '<%# DataBinder.Eval(Container.DataItem,"Date","{0:dd/MMM/yyyy HH:mm}") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="5%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton5" runat="server" forecolor="white" CommandName="sort" CommandArgument="Status">Status</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblStatus" text='<%# DataBinder.Eval(Container.DataItem,"Status") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>

</Columns>
</asp:DataGrid>
</p>
<p>
<asp:Label id="Label1" runat="server" visible="False"> DESC</asp:Label>
</p>
</form>
</td>
</tr>
</tbody>
</table>
</body>
</html>

recomm1.vb
-----------------------
Imports System.Data
Imports System.Data.OleDB

Public Class SortingTemplateColumns
Inherits System.Web.UI.Page
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
Protected WithEvents DropDownList1 AS System.Web.UI.WebControls.DropDownList
Protected WithEvents Label1 As System.Web.UI.WebControls.Label

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region


Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound

If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then

Select Case CType(e.Item.Cells(7).Text, String)

Case Is ="OPEN"

e.Item.BackColor = Drawing.Color.Red

Case Is ="CLOSED"

e.Item.BackColor = Drawing.Color.Orange

End Select

End If

End Sub


Sub Page_Load(ByVal Sender As System.Object, ByVal E As System.EventArgs) Handles MyBase.Load

If Not Page.IsPostBack Then

' Databind the data grid on the first request only
' (on postback, rebind only in paging and sorting commands)

BindGrid()

End If
End Sub

Sub DataGrid1_Page(ByVal Sender As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged

DataGrid1.CurrentPageIndex = e.NewPageIndex
BindGrid()

End Sub

Sub DataGrid1_Sort(ByVal Sender As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DataGrid1.SortCommand

DataGrid1.CurrentPageIndex = 0

SortField = e.SortExpression
if label1.text=" DESC" then
label1.text=" ASC"
else
label1.text= " DESC"
end if

BindGrid()

End Sub


'---------------------------------------------------------
'
' Helpers
'
' use a property to keep track of the sort field, and
' save it in viewstate between postbacks

Property SortField() As String

Get
Dim o As Object = ViewState("SortField")
If o Is Nothing Then
Return String.Empty
End If
Return CStr(o)
End Get

Set(ByVal Value As String)
ViewState("SortField") = Value
End Set

End Property


Sub BindGrid()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;"
ConnectionString += "Data Source=C:\Cryosat\database\recommendations.mdb"
Dim CommandText As String

CommandText = "SELECT * FROM recommendations order by recommendations.id DESC;"

Else

CommandText = "SELECT * FROM recommendations order by " & SortField & label1.text


End If

Dim myConnection As New OLEDBConnection(ConnectionString)
Dim myCommand As New OLEdbDataAdapter(CommandText, myConnection)

Dim objDataSet as new DataSet()

myCommand.Fill(objDataSet, "recommendations")
DataGrid1.DataSource=objDataSet.Tables("recommendations").defaultview

DataGrid1.DataBind()
DataGrid1.Columns(1).Visible=False

End Sub


Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e as System.EventArgs) Handles DropDownList1.SelectedIndexChanged

End sub

Public Sub DataGrid1_CommandItem (ByVal source as System.Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)


dim lblpage as New System.Web.UI.WebControls.Label

lblpage=e.Item.FindControl("lblpassID")

if e.CommandName = "View" then

Response.Redirect ("viewrecomm.aspx?id=" & lblpage.Text)

end if

if e.CommandName = "Edit" then

Response.Redirect ("Editrecomm.aspx?id=" & lblpage.Text)

end if

End sub

End Class
 
OK, i've made some streamlining and have got some parts working. But the problem seems to be that the Event for chosing the bg color does not see anything in the cells. In my new code, you will see that:
Case ""
e.Item.BackColor = System.Drawing.Color.White

it will background color everything white. here are the 2 files i''m using. Any help appreciated. I've read in another article that using boundcolumns instead of templatecolumns will make it work properly, but i need to use templatecolumns.

recomm2.vb
----------------------------

Imports System.Data
Imports System.Data.OleDB

Public Class SortingTemplateColumns
Inherits System.Web.UI.Page
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
Protected WithEvents DropDownList1 AS System.Web.UI.WebControls.DropDownList
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region

'---------------------------------------------------------
Public Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
If e.Item.ItemIndex > -1 Then
Select Case CType(e.Item.Cells(7).Text, String)
Case "OPEN"
e.Item.BackColor = System.Drawing.Color.Red
Case ""
e.Item.BackColor = System.Drawing.Color.White
Case "CLOSED"
e.Item.BackColor = System.Drawing.Color.Orange
Case Else
e.Item.BackColor = System.Drawing.Color.Black
End Select
End If
End Sub

'---------------------------------------------------------
Sub Page_Load(ByVal Sender As System.Object, ByVal E As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
' Databind the data grid on the first request only
' (on postback, rebind only in paging and sorting commands)
BindGrid()
End If
End Sub
'---------------------------------------------------------
Sub DataGrid1_Page(ByVal Sender As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged
DataGrid1.CurrentPageIndex = e.NewPageIndex
BindGrid()
End Sub
'---------------------------------------------------------
Sub DataGrid1_Sort(ByVal Sender As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DataGrid1.SortCommand
DataGrid1.CurrentPageIndex = 0
SortField = e.SortExpression
if label1.text=" DESC" then
label1.text=" ASC"
else
label1.text= " DESC"
end if
BindGrid()
End Sub
'---------------------------------------------------------
'
' Helpers
'
' use a property to keep track of the sort field, and
' save it in viewstate between postbacks
Property SortField() As String
Get
Dim o As Object = ViewState("SortField")
If o Is Nothing Then
Return String.Empty
End If
Return CStr(o)
End Get
Set(ByVal Value As String)
ViewState("SortField") = Value
End Set
End Property
'---------------------------------------------------------
Sub BindGrid()
' TODO: update the ConnectionString value for your application
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;"
ConnectionString += "Data Source=C:\Cryosat\database\recommendations.mdb"
Dim CommandText As String

' TODO: update the CommandText value for your application
If SortField = String.Empty Then
CommandText = "SELECT * FROM recommendations order by recommendations.id DESC;"
Else
CommandText = "SELECT * FROM recommendations order by " & SortField & label1.text
End If
Dim myConnection As New OLEDBConnection(ConnectionString)
Dim myCommand As New OLEdbDataAdapter(CommandText, myConnection)
Dim objDataSet as new DataSet()
myCommand.Fill(objDataSet, "recommendations")
DataGrid1.DataSource=objDataSet.Tables("recommendations").defaultview
DataGrid1.DataBind()
DataGrid1.Columns(1).Visible=False
End Sub
'---------------------------------------------------------
Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e as System.EventArgs) Handles DropDownList1.SelectedIndexChanged
End sub
'---------------------------------------------------------
Public Sub DataGrid1_CommandItem (ByVal source as System.Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
dim lblpage as New System.Web.UI.WebControls.Label
lblpage=e.Item.FindControl("lblpassID")
if e.CommandName = "View" then
Response.Redirect ("viewrecomm.aspx?id=" & lblpage.Text)
end if
if e.CommandName = "Edit" then
Response.Redirect ("Editrecomm.aspx?id=" & lblpage.Text)
end if
End sub
End Class

recomm2.aspx
------------------------

<form runat="server">
<p>
<font color="green">CryoSat Recommendations Page</font>
</p>
<p>
<a href="newrecomm.aspx"><span style="FONT: 10pt verdana, arial; COLOR: black">Add
new </span></a>
<asp:DataGrid id="DataGrid1" runat="server" OnItemDataBound="DataGrid1_ItemDataBound" OnItemCommand="DataGrid1_CommandItem" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BorderStyle="Solid" BorderWidth="1px" BorderColor="#999999" BackColor="White" CellPadding="3" GridLines="Vertical" ForeColor="Black" Width="100%">
<FooterStyle backcolor="#CCCCCC"></FooterStyle>
<HeaderStyle font-names="Arial" font-bold="True" horizontalalign="Center" forecolor="White" backcolor="Black"></HeaderStyle>
<PagerStyle horizontalalign="Center" forecolor="Black" backcolor="#999999" mode="NumericPages"></PagerStyle>
<SelectedItemStyle font-bold="True" forecolor="White" backcolor="#000099"></SelectedItemStyle>
<Columns>
<asp:TemplateColumn>
<HeaderStyle width="5%"></HeaderStyle>
<ItemTemplate>
<asp:ImageButton CommandName="View" ImageUrl="images/click-up.gif" runat="server" AlternateText="See details" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="5%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton1" runat="server" forecolor="White" CommandName="sort" CommandArgument="id">ID</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblpassID" text='<%# DataBinder.Eval(Container.DataItem,"id") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="10%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton2" runat="server" forecolor="white" CommandName="sort" CommandArgument="Date">Date</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblDate" text= '<%# DataBinder.Eval(Container.DataItem,"Date","{0:dd/MMM/yyyy HH:mm}") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="5%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton6" runat="server" forecolor="white" CommandName="sort" CommandArgument="Number">Number</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<div align="center">
<asp:Label id="lblNumber" text='<%# DataBinder.Eval(Container.DataItem,"Number") %>' runat="server" />
</div>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="10%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton4" runat="server" forecolor="white" CommandName="sort" CommandArgument="Author">Author</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblAuthor" text='<%# DataBinder.Eval(Container.DataItem,"Author") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="45%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton3" runat="server" forecolor="white" CommandName="sort" CommandArgument="Details">Details</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblDetails" text='<%# DataBinder.Eval(Container.DataItem,"Details") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="5%"></HeaderStyle>
<HeaderTemplate>
<asp:LinkButton id="LinkButton5" runat="server" forecolor="white" CommandName="sort" CommandArgument="Status">Status</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="lblStatus" text='<%# DataBinder.Eval(Container.DataItem,"Status") %>' runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderStyle width="5%"></HeaderStyle>
<ItemTemplate>
<asp:imageButton CommandName="Edit" ImageUrl="images/Edit.gif" runat="server" AlternateText="Edit this pass log" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</p>
<p>
<asp:Label id="Label1" runat="server" visible="False"> DESC</asp:Label>
</p>
</form>
 
Well, i'm not fan of this control but as it's not subject here i propose to take a look at this article that describes how to change a color of individual cell depending upon its value ... i guess if you find sense there you will easy color entire row after that.
http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c44c.aspx#q745q

Cheers ;)
 
Hi. THanks for the reply, but it doesnt really help me. I've looked through that article already(as i have many many other articles) and it doesnt help. that article uses about 8 different files to achieve the same thing! my question is a bit more specific, i'm not asking for a different way to implement this datagrid formatting, i want to know how i can make this method work.
The basic problem is the Event which decides which color to make the row, does not see anything in the cell that it is checking. Someone else said that if you use Boundcolumns instead or Templatecolumns, it should work, why wont it work with templatecolumns? i need templatecolumns because i have images in some of the cells.
Thanks. Any ideas?
 
"Num" is another Data Field from same table.
Hope it helps



Private Sub dgRpt_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgRpt.ItemDataBound
Try

If e.Item.ItemType <> ListItemType.Header Then

If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then

If e.Item.Cells(1).Text = "UNFILLED" Then

Dim lbl As Label = e.Item.FindControl("lblNmLink")

Dim hl As New HyperLink

hl.NavigateUrl = "../Blank.aspx"

hl.Target = "_blank"

hl.Text = "Nominate An Individual"

lbl.Controls.Add(hl)

Else

e.Item.Cells(2).BackColor = Color.Gainsboro

e.Item.Cells(2).ForeColor = Color.Black

Dim lbl As Label = e.Item.FindControl("lblNmLink")

lbl.Text = e.Item.Cells(1).Text

End If

Dim i As Integer

For i = 0 To e.Item.Cells.Count - 1

If e.Item.DataItem("NUM") = 2 Then e.Item.Cells(3).BackColor = Color.LightGreen

If e.Item.DataItem("NUM") = 4 Then e.Item.Cells(3).BackColor = Color.LightGreen

If e.Item.DataItem("NUM") = 10 Then

e.Item.Cells(3).BackColor = Color.Peru

e.Item.Cells(3).ForeColor = Color.White

End If

If e.Item.DataItem("NUM") > 10 Then e.Item.Cells(3).BackColor = Color.Tomato

Next

End If

End If

Catch ex As Exception

ErrorCapture(Form1, ex)

End Try

End Sub

 
Back
Top