简体   繁体   中英

Set ASP DataGrid row color based on cell value

I have an ASP:DataGrid which I am displaying records in. The records are pulled from an SQL Server 2008 R2 database in to an SqlAdapter which in is used to fill a DataSet and that is bound to the ASP:DataGrid

The ASP:DataGrid can span multiple pages and is limited to 20 records per page.

One of the columns is a value for how many days are remaining for the entry to be dealt with. I want to highlight any which have a value 0 - 1 as red and any 2 - 5 as oracle. The method I have tried is to set a function call to the OnItemDataBound field of the ASP:DataGrid

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(5).Text, Integer)
            Case 0 To 1
                e.Item.BackColor = Drawing.Color.Red
            Case 2 To 5
                e.Item.BackColor = Drawing.Color.Orange
        End Select
    End If
End Sub

This works perfectly when the page first loads. If there are more than one page of records and you try to move to the next page, no records load at all and in fact the ASP:DataGrid doesn't display at all. If I remove the OnItemDataBound then the ASP:DataGrid functions normally again (albeit without the highlights).

So it turned out that may code was actually correct. I put a Try block around the code with a section in the Catch part to log the details in a table in my database.

Straight away it showed the following coming from the Select Case

Conversion from string " " to type 'Integer' is not valid.

A simple change to ensure that the cell is only coloured when a valid value is present is all I needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM