DataGrid Cell Formatting and ASP.Net

Hi

I am using a datagrid to display the contents of a table.  I need to be able to change the color of a cell called GlobalRisk if a number is greater than 10.  Can any one suggest if and how I can format just the cell of the datagrid and not the entire grid?  Can I use an if/then statement to format a datagrid cell? Here is the relevant code.

Sub Page_Load

  If Not isPostBack Then
    BindDataGrid( "ARN" )
  End If
 
 
End Sub

Sub BindDataGrid( strSortField As String )
  Dim conPubs As OLeDBConnection
  Dim cmdSelect As OLeDBCommand
  Dim dadTitles As OLeDBDataAdapter
  Dim dstTitles As DataSet

  dim sXMLFile as string
    dim sMDBFile as string
        dim sConn as string
    dim sSQL as string
      sMDBFile = MapPath("~/Audit/Audit.mdb")
      SConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
      Sconn = Sconn & "Data Source=" & sMDBFile
      dim cnn  as OLeDbConnection
      dim cmd as OLeDbCommand
      dim objDA  as OLeDBDataAdapter
      dim objDS  as Dataset
      cnn = New OLeDbConnection(sConn)
      cnn.Open()

      
  cmdSelect = New OLeDBCommand( "Select * From tblEntity Order By " & strSortField, cnn )
 
  dgrdTitles.DataSource = cmdSelect.ExecuteReader()
  dgrdTitles.DataBind()
  cnn.Close()
End Sub

Sub dgrdTitles_SortCommand( s As Object, e As DataGridSortCommandEventArgs )
  BindDataGrid( e.SortExpression )
End Sub

**AND THIS IS THE COLUMN AND CELL  I WISH TO FORMAT IF THE VALUE IS GREATER THAN 10 ***

  <asp:DataGrid
  ID="dgrdTitles"
  AllowSorting="True"
  OnSortCommand="dgrdTitles_SortCommand"
  AutoGenerateColumns="False"
  CellPadding="10"
  HeaderStyle-Font-Name="Arial"
  HeaderStyle-Font-Size="11pt"
  HeaderStyle-Font-Bold="True"
  HeaderStyle-BackColor="LightBlue"
  ShowFooter="True"
  FooterStyle-Font-Name="Arial"
  FooterStyle-Font-Size="10pt"
  FooterStyle-Font-Bold="True"
  FooterStyle-BackColor="LightCyan"
  BorderColor="Gray"
  ItemStyle-Font-Name="Arial"
  ItemStyle-Font-Size="9pt"
  ItemStyle-Font-Bold="False"
  ItemStyle-BackColor="AliceBlue"
    Runat="Server">


***THE RELEVANT COLUMN/CELL **
<asp:BoundColumn
    HeaderText="Global Risk Score"
    DataField="GlobalRisk"
    SortExpression="GlobalRisk"
      FooterText="Global Risk Score"/>

dolbsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

faifaiCommented:
you have to do this in ItemDataBound of your dataGrid. You can take a look at the following link

http://www.codeproject.com/aspnet/ItemCreated.asp


and here

http://carlosag.net/Tools/CodeTranslator/Default.aspx

to convert the code to VB.net
toocrazy007Commented:
write the following code in your itemdatabound

Private Sub GridDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
 If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
   Dim rv As DataRowView = CType(e.Item.DataItem, DataRowView)
'assume that your required column is in 5row of array
   Dim nUnitsInStock As Int32 = Convert.ToInt32(rv.Row.ItemArray(4))  
   If nUnitsInStock < 10 Then
     e.Item.Cells(4).BackColor = Color.Red
   End If
 End If
End Sub

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dolbsAuthor Commented:
Thanks

Where is the itemdatbound placed?

and the page will not compliel because of an error in this line  e.Item.Cells(4).BackColor = Color.Red

It says the Color.Red is undeclared so it does not recognise the color function.
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

toocrazy007Commented:
you have to import System.Drawing namespace to work with color property
dolbsAuthor Commented:
Okay. Sorry for the dumb questions.  New to asp.net  Color problem sorted.  Figured that out myself. thanks to "toocrazy007" anyway, but the code will still not compile.
I keep getting an " invalid cast exception" See the commented section below.
I am using the  OnItemDataBound = "GridDataBound" to call the sub.  Id this correct?

Here is the entire code (important parts) as it now stands

Sub BindDataGrid( strSortField As String )
  Dim conPubs As OLeDBConnection
  Dim cmdSelect As OLeDBCommand
  Dim dadTitles As OLeDBDataAdapter
  Dim dstTitles As DataSet

  dim sXMLFile as string
    dim sMDBFile as string
        dim sConn as string
    dim sSQL as string
      sMDBFile = MapPath("~/Audit/Audit.mdb")
      SConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
      Sconn = Sconn & "Data Source=" & sMDBFile
      dim cnn  as OLeDbConnection
      dim cmd as OLeDbCommand
      dim objDA  as OLeDBDataAdapter
      dim objDS  as Dataset
      cnn = New OLeDbConnection(sConn)
      cnn.Open()

      
  cmdSelect = New OLeDBCommand( "Select * From tblEntity Order By " & strSortField, cnn )
 
  dgrdTitles.DataSource = cmdSelect.ExecuteReader()
  dgrdTitles.DataBind()
  cnn.Close()
End Sub

Private Sub GridDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
 If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
 Dim rv As DataRowView = CType(e.Item.DataItem, DataRowView) '///// invalid cast exception
'assume that your required column is in 4th row of array
   Dim nUnitsInStock As Int32 = Convert.ToInt32(rv.Row.ItemArray(3))  
   If nUnitsInStock = 10 Then
     e.Item.Cells(3).BackColor = Color.Red
   End If
 End If
End Sub


Sub dgrdTitles_SortCommand( s As Object, e As DataGridSortCommandEventArgs )
  BindDataGrid( e.SortExpression )
 
End Sub


'and the datagrid layout
 <asp:DataGrid
  ID="dgrdTitles"
  AllowSorting="True"
  OnSortCommand="dgrdTitles_SortCommand"
  OnItemDataBound = "GridDataBound"   ' //// Is this correct?
  AutoGenerateColumns="False"
  CellPadding="10"
  HeaderStyle-Font-Name="Arial"
  HeaderStyle-Font-Size="11pt"
  HeaderStyle-Font-Bold="True"
  HeaderStyle-BackColor="LightBlue"
  ShowFooter="True"
  FooterStyle-Font-Name="Arial"
  FooterStyle-Font-Size="10pt"
  FooterStyle-Font-Bold="True"
  FooterStyle-BackColor="LightCyan"
  BorderColor="Gray"
  ItemStyle-Font-Name="Arial"
  ItemStyle-Font-Size="9pt"
  ItemStyle-Font-Bold="False"
  ItemStyle-BackColor="AliceBlue"
    Runat="Server">
      
      
<Columns>
     <asp:BoundColumn
    HeaderText="ID"
    DataField="ID"
    SortExpression="ID"
      FooterText="ID"/>

     <asp:BoundColumn
    HeaderText="ARN"
    DataField="ARN"
    SortExpression="ARN"
      FooterText="ARN"/>

      <asp:BoundColumn
    HeaderText="Legal Entity"
    DataField="Entity"
    SortExpression="Entity"
      FooterText="Legal Entity"/>
      
      <asp:BoundColumn
    HeaderText="Global Risk Score"
    DataField="GlobalRisk"
    SortExpression="GlobalRisk"
         FooterText="Global Risk Score"/>

      <asp:BoundColumn
    HeaderText="Level"
    DataField="GlobalColor"
    SortExpression="GlobalColor"
      FooterText="Level"/>
      
 
</Columns>

</asp:DataGrid>


toocrazy007Commented:
Both the things, assigning method to onItemDataBound,  and the type casting is also right, i didn't found any error in that please debug the code and see weather you are getting data correctly / not.
dolbsAuthor Commented:
When I removed the datagrid sort command and replaced it with an edit command the page complied but the cell did not change colour.  If the 4th column in the database holds the value then the (rv.Row.ItemArray(3))  is 3 as shown with the first column being row zero.  Is this correct.
 
dolbsAuthor Commented:
Thank you all for your help.  Unfortunately none of the suggested answers worked properly.  I have been experimenting and solved the problem by using this code:
And by changing the datagrid from OnDataBound to "OnItemDataBound"

Private Sub GridDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
 Dim nUnits As Integer
  nUnits = CInt(e.Item.Cells(2).Text)
  If nUnits >= 12 Then
    e.Item.Cells(2).BackColor = Color.Red
    e.Item.Cells(2).Font.Bold = True
  Else If nUnits < 12 and nUnits >= 10 Then
    e.Item.Cells(2).BackColor = Color.Yellow
    e.Item.Cells(2).Font.Bold = True
Else If nUnits < 10 and nUnits >= 7 Then
    e.Item.Cells(2).BackColor = Color.LightGreen
        Else
    e.Item.BackColor = Color.White
    End If
End If
End Sub
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.