Link to home
Start Free TrialLog in
Avatar of bibmed2
bibmed2Flag for Poland

asked on

Change color of GridView's Rows according to data from database

I`d like to display news on my webpage from database. The news are 2 types - normal and important (importance 0/1). Below is my code. The problem is how can I display important news in red color and rest in black ?  In asp or php I`ve used sth like this: "If importance=1..." but what I should do in  ASP.NET ?

(ASP.NET 3.5, C#, SQL SERVER 2005 EXPRESS)
<asp:SqlDataSource 
          ID="SqlDataSourceNews" runat="server" 
          ConnectionString="<%$ ConnectionStrings:bm_wwwConnectionStringWriter %>" 
          SelectCommand="SELECT [idNews], [shortNews], [longNews], [addDate], [importance], [position], [status] FROM [news] WHERE [status] = 1 ORDER BY [addDate]">
        </asp:SqlDataSource>
        <asp:GridView ID="GridViewNews" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceNews" Width="440px" GridLines="None" ShowHeader="False" >
          <Columns>       
            <asp:TemplateField>
              <ItemTemplate>
               <a href="moreNews.aspx#<%# Eval("idNews") %>"> <%# Eval("shortNews") %></a>
                
				        <div id="addNewsText">Data dodania: <%# Eval("addDate", "{0:dd/MM/yyyy}") %></div>
                <hr />
              </ItemTemplate>                 
            </asp:TemplateField>
          </Columns>
        </asp:GridView>

Open in new window

Avatar of abel
abel
Flag of Netherlands image

You could create a one-liner with IIF(expr, truepart, falsepart) but that may easily clutter your code. I'd prefer to do it in the databind event of any asp object that's inside the ItemTemplate. The latter would give you more control.
Suppose you put the following inside the ItemTemplate:

<asp:LinkButton OnDataBinding="LinkNews_DataBinding"
    CommandArgument='<%# Eval("idNews") %>'
    OnClick="hypWinkelwagent_event" >
 
    <%# Eval("shortNews") %>
</asp:LinkButton>
<div id="addNewsText">Data dodania: <%# Eval("addDate", "{0:dd/MM/yyyy}") %></div>

Open in new window

(the above would replace your current hand-crafted a-tag).

Then, in the code behind, you can do the following:

// handle changing color
protected void LinkNews_DataBinding(object sender, EventArgs e)
{
    LinkButton link = (LinkButton) sender;
    GridViewRow row = (GridViewRow)link.NamingContainer;
    row.Style.Add("color", ....  do your color logic ...)
    // do stuff to your link as well
}
 
// handle showing details 
protected void LinkNew_Command(object sender, CommandEventArgs e)
{
    LinkButton link = (LinkButton)sender;
    // show details by using:
    link.CommandArgument;
}

Open in new window

So, if you take that path, you better two things at once:
  1. Use the code-behind to control the data-driven layout of the link and/or the row
  2. Use the code-behind to control how to show the details (which you should expand by using a DetailsView which you show using the LinkNew_Command)
Maybe this all is more information then you wanted, but I believe this would bring you to a better control of your application and in the meantime tackle your problem at hand in a controlled manner :)
Avatar of bibmed2

ASKER

Thank for your answer. I see You use onclick event so I should click LinkButton to change color. I`d like to set color during listing of records. For example :

If (importance=1) = 1 then
Response.Write ("" & news & "")
else
Response.Write ("" & news & "")
end if  


No, I don't use the onclick even, I meant the databinding event.

The onCommand (different from OnClick) event was added to show you how you could more easily deal with links by using asp:LinkButton. That was not your question, just something I added.

The code you show is VB. What is the actual code you use? Because you posted to the C# list.

It is recommended NOT to use Response.Write. They are (quite, but not totally) dead since .NET was introduced. Of course, if you want to do it that way, I can show you how you can ;-)
Avatar of bibmed2

ASKER

Maybe my question isn`t clear.  I`ll try once again.

The code in VB
If (importance=1) = 1 then
Response.Write ("" & news & "")
else
Response.Write ("" & news & "")
end if  

is only the example what I want to do. I know asp, php but I`m learning C# so I have no idea how to reach the above effect in it.

I`ll try to explain my problem once again:

1. I have database with news.

CREATE TABLE [dbo].[news](
      [idNews] [int] IDENTITY(1,1) NOT NULL,
      [shortNews] [nvarchar](200) NOT NULL,
      [longNews] [ntext] NULL,
      [addDate] [datetime] NOT NULL,
      [importance] [int] NOT NULL CONSTRAINT [DF_news_importance]  DEFAULT ((0)),
      [position] [int] NULL,
      [status] [int] NOT NULL CONSTRAINT [DF_news_status]  DEFAULT ((1)),
 CONSTRAINT [PK_news] PRIMARY KEY CLUSTERED

2. The field importance divided news into two groups 0-normal news (black color) and 1-important news (red color)

3. I`d like to list all news on webpage.

4. During listing if importance = 1 news should be in red if importance = 0 news should be in black

I know how to do it in asp, php but I`m new in .NET C# so please explain me how to do it correctly (of course not using response.write :))

I`m able to list all news but only in black (look at my code in first post)

thanks in advance
Sorry. I never used that syntax with business logic, and I seem to be incorrect: you cannot use Response.Write with data that is databound.

Instead, if you must use a font tag, you can do it as follows:

<ItemTemplate>
    <font runat="server" ondatabinding="font_databinding">
          your link etc
    </font>
</ItemTemplate>

Open in new window

With this in the code behind, which will give you the proper color:

protected void font_databinding(object sender, EventArgs e)
{
    HtmlGenericControl font = (HtmlGenericControl)sender;
    GridViewRow row = (GridViewRow)font.NamingContainer;
    int colorCode = Int32.Parse(DataBinder.Eval(row.DataItem, "importance").ToString());
    if(colorCode == 1)
        font.Attributes.Add("color", "red");
    else
        font.Attributes.Add("color", "blue");
}

Open in new window

Avatar of bibmed2

ASKER

Could You post all html code too ?
ASKER CERTIFIED SOLUTION
Avatar of abel
abel
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bibmed2

ASKER

Thank you for help.
Glad it worked for you eventually! Tx for the points ;)