Linq Gridview - changing the style of the gridview depending on its database values

Posted on 2008-11-07
Last Modified: 2013-11-11
Hi experts,

I started using Linq in my projects to fill my gridview.
Now I have the following problem:
I have a table field "active" which tells me if an record in that table is active or not.
If it's not active, I would like to display that record in the gridview in a different style (ie. different fore-color for that row)

Can anyone help me in accomplishing this
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 

            AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ID"

            DataSourceID="SourceDB" ForeColor="#333333" GridLines="None" 

            OnRowCommand="gridView1_Command" PageSize="20" OnRowUpdated="gridView1_RowUpdated">

            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />


                <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" 

                    SortExpression="ID" InsertVisible="False" />

                <asp:BoundField DataField="CounterNationals" HeaderText="#Nationals" 

                    SortExpression="CounterNationals" />

                <asp:BoundField DataField="SalespersonCode" HeaderText="SPCode" SortExpression="SalespersonCode" />

                <asp:BoundField DataField="Name" HeaderText="Name" 

                    SortExpression="Name" />

                <asp:BoundField DataField="FirstName" HeaderText="FirstName" 

                    SortExpression="FirstName" />

                <asp:BoundField DataField="Institution" HeaderText="Institution" 

                    SortExpression="Institution" />

                <asp:BoundField DataField="City" HeaderText="City" 

                    SortExpression="City" />

                <asp:BoundField DataField="Country" HeaderText="Country" 

                    SortExpression="Country" />           

                    <asp:TemplateField HeaderText="CongressTicket" SortExpression="CongressTicket">





                            <asp:DropDownList ID="ddlCongressTicket" runat="server" AutoPostBack="True"  DataSourceID="TicketDataSource"

                                 SelectedValue='<%# Bind("CongressTicket") %>'>


                            <asp:LinqDataSource ID="TicketDataSource" runat="server" ContextTypeName="TicketValues" TableName="AvailableTicketValues" />



                <asp:CheckBoxField DataField="EveningEvent" HeaderText="EveningEvent" 

                    SortExpression="EveningEvent" />

                <asp:CheckBoxField DataField="AccompanyPerson" HeaderText="Add. person" 

                    SortExpression="AccompanyPerson" />

                <asp:BoundField DataField="TotalAmount" HeaderText="Open Amount" SortExpression="TotalAmount" />

                <asp:TemplateField HeaderText="Distributor" SortExpression="Distributor.DistriName">


                        <%#Eval("Distributor.DistriName") %>



                        <asp:DropDownList ID="ddlDistris" runat="server" AutoPostBack="True" DataSourceID="DistributorDataSource"

                            DataTextField="DistriName" DataValueField="ID" SelectedValue='<%# Bind("DistriID") %>'>


                        <asp:LinqDataSource ID="DistributorDataSource" runat="server" ContextTypeName="EventManager.Event"

                            Select="new (ID, DistriName)"  TableName="Distributor">




                <asp:CommandField ShowEditButton="True"  ButtonType="Image" 






                        <asp:ImageButton ID="delete" Runat="server" ImageUrl="~/Controls/Images/cross.gif"

                            OnClientClick="return confirm('Are you sure you want to delete this record?');"

                      CommandName="Delete" CommandArgument="<%# Container.DataItemIndex %>">




                <asp:ButtonField ButtonType="Image" ImageUrl="~/Controls/Images/details2.gif" CommandName="CallDetails"/>


            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

            <EditRowStyle BackColor="#999999" />

            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />


Open in new window

Question by:arthrex
    LVL 4

    Accepted Solution

    This should be fairly straightforward. Here are the steps I recommend and code snippet below:

    - Intercept the GridView OnRowDataBound event handler. This event handler receives an instance of a GridViewRowEventArgs.
    - The GridViewRowEventArgs has a Row property, and the Row property has a DataItem property that contains an instance of your bound data for rows that are data rows. Notice the RowType check in the code snippet.
    - Inspect the data item, if it meets the criteria, change the style on the row or the individual elements.

    My code snippet assumes a schema with a person table, and a linqdatasource query against this table. The gridview is databound to this datasource. If the firstname in the row contains "Dave" then the row is made red. The commented code is for cases where I just want to color the cell value. To do this, I first converted the <asp:BoundField> to an <asp:TemplateField> and then did a FindControl() against the row, looking for the label.

    For this to work, the following needs to be added to the GridView in the aspx:


    Let me know if this helps.

    protected void Person_DataBound(object sender, GridViewRowEventArgs e)
       GridViewRow row = e.Row;
       if (row.RowType == DataControlRowType.DataRow)
          person p = row.DataItem as person;
          if (p.firstname.Contains("Dave"))
             row.ForeColor = Color.Red;
    	//Label labelFirstName = row.FindControl("labelFirstName") as Label;
    	//labelFirstName.ForeColor = Color.Red;

    Open in new window


    Author Comment

    Perfect answer!

    Featured Post

    Gigs: Get Your Project Delivered by an Expert

    Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

    Join & Write a Comment

    In my previous two articles we discussed Binary Serialization ( and XML Serialization ( In this article we will try to know more about SOAP (Simple Object Acces…
    Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    754 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

    Need Help in Real-Time?

    Connect with top rated Experts

    25 Experts available now in Live!

    Get 1:1 Help Now