change color data displayed in a datagrid.

hi
pls suggest me a solution as i am stuck up since long on this.
i have a datagrid which has only one column ... all these are hyperlinks.
i want to have a condition such that if the flag value in the table is null then the color shoudl be green else blue.

here is the code of the aspx page datagrid defination:
<asp:datagrid id="dgVersion" runat="server" AutoGenerateColumns="False" ShowFooter="True" OnItemDataBound="dgVersion_ItemDataBound">
                  <Columns>
                        <asp:TemplateColumn HeaderText="Server List" HeaderStyle-Font-Bold="True">
                              <ItemTemplate>
                                    <asp:HyperLink id="AttachmentLink" Target="main" runat="server" NavigateUrl='<%# "ServerMain2.aspx?ID=" & Server.UrlEncode(Container.DataItem("IDKey")).Tostring()%>'>
                                          <%#DataBinder.Eval(Container.DataItem,"ServerName")%>
                                    </asp:HyperLink>
                              </ItemTemplate>
                        </asp:TemplateColumn>
                  </Columns>
            </asp:datagrid>

and i want to have a condition in codebehind which wud change the color .this is a test code i put at the back in codebehind.why is the color not changing at all.what mistake i am doing. i am struggling since long. pls suggest me someone.
thanks a lot

Sub dgVersion_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgVersion.ItemDataBound
        Dim itemType As ListItemType = e.Item.ItemType
        If (e.Item.ItemType = ListItemType.Item Or _
          e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.EditItem) Then

            'If e.Item.Cells(1).Text = "APPLICATION" Then
            If CType(e.Item.FindControl("AttachmentLink"), HyperLink).Text = "APPLICATION" Then
                e.Item.BackColor = Color.Red
            Else
                e.Item.ForeColor = Color.Green
            End If

        End If
    End Sub
LVL 1
samir25Asked:
Who is Participating?
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.

nauman_ahmedCommented:
You need to check the value on DataGrid_ItemCreated event :)

Sub dgVersion_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgVersion.ItemCreated
        Dim itemType As ListItemType = e.Item.ItemType
        If (e.Item.ItemType = ListItemType.Item Or _
          e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.EditItem) Then

            'If e.Item.Cells(1).Text = "APPLICATION" Then
            If CType(e.Item.FindControl("AttachmentLink"), HyperLink).Text = "APPLICATION" Then
                e.Item.BackColor = Color.Red
            Else
                e.Item.ForeColor = Color.Green
            End If

        End If
    End Sub

HTH, Nauman.
NowaYCommented:
Do this as I suggested in the other thread:

SELECT employees.pk_key, employees.name, empDetails.flagTF
FROM employees INNER JOIN empDetails ON employees.pk_key= empDetails.pk_key;


then do this:


<asp:datagrid id="dgVersion" runat="server" AutoGenerateColumns="False" ShowFooter="True" OnItemDataBound="dgVersion_ItemDataBound">
               <Columns>
         <asp:BoundColumn DataField="flagTF" visible="false" HeaderText="flagTF"></asp:BoundColumn>
                    <asp:TemplateColumn HeaderText="Server List" HeaderStyle-Font-Bold="True">
                         <ItemTemplate>
                              <asp:HyperLink id="AttachmentLink" Target="main" runat="server" NavigateUrl='<%# "ServerMain2.aspx?ID=" & Server.UrlEncode(Container.DataItem("IDKey")).Tostring()%>'>
                                   <%#DataBinder.Eval(Container.DataItem,"ServerName")%>
                              </asp:HyperLink>
                         </ItemTemplate>
                    </asp:TemplateColumn>
               </Columns>
          </asp:datagrid>




Public Sub dgVersion_ItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgVersion.ItemDataBound
        Dim itemType As ListItemType = e.Item.ItemType

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

                    If e.Item.Cells(0).Text <> "" Then
                        e.Item.BackColor = Color.Red
                   else
                        e.Item.BackColor = Color.Blue
                    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
MajinLokiCommented:
you could wrap the link in a div tag and use a CSS to define the color, etc.  (this way if you wanted to change the colors in the future you can edit the CSS without changing the code behind.  You could also apply this to directly editing the link color by returning the color value or string woth the getColor method.

<div class="<%# getColor(Convert.ToString(DataBinder.Eval(Container, "DataItem.flag"))) %>">

<asp:HyperLink id="AttachmentLink" Target="main" runat="server" NavigateUrl='<%# "ServerMain2.aspx?ID=" & Server.UrlEncode(Container.DataItem("IDKey")).Tostring()%>'>
                                   <%#DataBinder.Eval(Container.DataItem,"ServerName")%>
                              </asp:HyperLink>

</div>

then in the codebehind write a public method getColor that returns a string name fr the CSS based on the value of the flag, which will come in as a parameter.

public string getColor(string flag)
{
     if(flag == null)
     {
          return "greenClass";
     }
     else
     {
          return "blueClass";
     }
}

Then in the CSS define 2 classes and set the properties for each class.  This is easily changeable and adaptable.
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

rinkujainCommented:
- first thing u r using 2 different property
   e.Item.BackColor = Color.Red
            Else
                e.Item.ForeColor = Color.Green
 one is forecolor and other is backcolor

-now if u change backcolor then it will apply for all the cell, but if forecolor then it won't apply for hyperlink, for it u have to give it like
CType(e.Item.FindControl("AttachmentLink"), HyperLink).Forecolor=color u want

samir25Author Commented:
hi rinku..actually i see no change in forecolor or backcolor or anywhere ! it just doenst reflet any change in color.
bu ti am using itembound.not itemcreated,let me try that
samir25Author Commented:
i thinks its a very strange problem.maybe u exp people can explain my why.
i am using this file serverList2.aspx on hte left side as a frame.when i run it its running fine.but when i just now check in the vs.net design mode inside the other aspx file, where i inserted it on the left then i see this error:
'dgversion_itemDataBound' is not a member of serverlist2.aspx

why is this so?it means its not going to the codebehind at all! thats why i see no color change;can someone pls respond.what do i need to do.
rinkujainCommented:
whats the access modifier for 'dgversion_itemDataBound' ? is it public or private?
samir25Author Commented:
hi rinku i had resolved this prob. now i am stuck up as to how to color code based on the condition from the database. i want to test that if the column vlaue of the db is empty the i want the vlaue in datagrid to be green else red.

hwo do i refer the value of a datanbase???
i hope i am clear.

rinkujainCommented:
you accepted the answer, so ur prob has solved or still have some issue?
samir25Author Commented:
actualy its kinda a solved as i figured out how to check the condition:
If objDataReader("ApproveUser") = "" Then
             e.Item.BackColor = Color.Red
           Else
               e.Item.BackColor = Color.Blue
            End If

but nwo i am getting an error Operator is not valid for type 'DBNull' and string "".
for one of the records
rinkujainCommented:
ok, just check :
If  (ISDBNULL(objDataReader("ApproveUser") OR objDataReader("ApproveUser") = "" )Then
             e.Item.BackColor = Color.Red
           Else
               e.Item.BackColor = Color.Blue
            End If

AS ERROR COMING BCOZ OF NULL VALUE COMING FOR THIS FIELD, ELSE DO CHANGE IN STORED PROC FOR NULL CHECKING AS PER YOUR DATABASE
samir25Author Commented:
i stil get this error

Operator is not valid for type 'DBNull' and string "".
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Operator is not valid for type 'DBNull' and string "".

Source Error:


Line 86:         If (e.Item.ItemType = ListItemType.Item Or _
Line 87:           e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.EditItem) Then
Line 88:             If (IsDBNull(objDataReader("ApproveUser")) Or objDataReader("ApproveUser") = "") Then
Line 89:                 e.Item.BackColor = Color.Red
Line 90:             Else
 
rinkujainCommented:
ok in vb it is evaluating both the expression, so now try this:
If not  (ISDBNULL(objDataReader("ApproveUser") ) then
         if objDataReader("ApproveUser") = "" )Then
             e.Item.BackColor = Color.Red
           Else
               e.Item.BackColor = Color.Blue
            End If
else
             e.Item.BackColor = Color.Red
end if
samir25Author Commented:
ok just saw ur mess let me try this
samir25Author Commented:
it works well.,...great rinku!
when i use back color the cells gets filled by red color.what property i need to use to color the text.i tried forecolor aslo with that nothign happens
rinkujainCommented:
ok
i think u forgot my previous comment, i written to change fprecolor of hyperlink u have to first refer that hyperlink then make that object forecolor property to red

dim lnk as hyperlink
lnk=cytpe(e.item.findcontrol("controlname"),hyperlink)
lnk.forecolor=ur color
samir25Author Commented:
great rinku it works..now i can move ahead with rest of the code.thansk a lot!
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
ASP.NET

From novice to tech pro — start learning today.