?
Solved

DataGrid Cell Formatting and ASP.Net

Posted on 2006-04-10
8
Medium Priority
?
691 Views
Last Modified: 2012-06-27
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"/>

0
Comment
Question by:dolbs
  • 4
  • 3
8 Comments
 
LVL 2

Expert Comment

by:faifai
ID: 16423460
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
0
 
LVL 2

Accepted Solution

by:
toocrazy007 earned 1000 total points
ID: 16423793
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
0
 

Author Comment

by:dolbs
ID: 16434363
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.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 2

Expert Comment

by:toocrazy007
ID: 16435709
you have to import System.Drawing namespace to work with color property
0
 

Author Comment

by:dolbs
ID: 16450708
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>


0
 
LVL 2

Expert Comment

by:toocrazy007
ID: 16451346
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.
0
 

Author Comment

by:dolbs
ID: 16451576
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.
 
0
 

Author Comment

by:dolbs
ID: 16504725
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
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month16 days, 13 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question