What is the method for changing the background color of rows in a grid

Within my asp.net application, I am implementing a grid-view control where I am populating data into a label element within the grid-view.
If the data happens to be empty, I want the row color to be displayed in red.
However, if there is data to bind, I would like the row color to be green. Here is the code snippet I am using:

<asp:TemplateField HeaderText="Holiday Region">
     <ItemTemplate>
         <asp:Label ID="lblholdareg" runat="server" Text='<%# Eval("Holidaregion") %>'>
         </asp:Label>
     </ItemTemplate>
</asp:TemplateField>

Answer №1

To customize the appearance of rows in a GridView, utilize the RowDataBound event. Access the e.Row item and apply a CSS class or set the background color directly. Using a CSS class allows for easier design modifications without the need for recompilation.

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Holiday Region">
            <ItemTemplate>
                <asp:Label ID="lblholdareg" runat="server" Text='<%# Eval("Holidaregion") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In the code-behind, assuming a DataTable is used as the data source. Adjust the code according to your data structure:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    System.Data.DataRow row = (System.Data.DataRow)e.Row.DataItem;
    if (row["Holidaregion"] == null || row["Holidaregion"].ToString().Trim().Length == 0)
    {
        e.Row.CssClass = "row-empty";
    }
    else 
    {
        e.Row.CssClass = "row-full";
    }
}

Answer №2

To achieve this, you need to utilize the rowdatabound function within the context of a gridview.

protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
         //Adjust the code based on cell number or element identification
         if(e.Row.Cells[0].Text != "")
            e.Row.BackColor = Color.Green;
         else
            e.Row.BackColor = Color.Red;   
    }
}

Answer №3

if(e.Row.RowType == DataControlRowType.DataRow)
{
    Control label = e.Row.FindControl("Label1");
  ((Label)label).BackColor = System.Drawing.Color.Red;
}

Answer №4

Consider trying out the following approach

<asp:TemplateField HeaderText ="Holiday Region">
  <ItemTemplate >
    <asp:Label ID ="lblholdareg" runat ="server"
     CSSClass='<%# (String.IsNullOrEmply(Eval("Holidaregion")))?"red:green" %>' 
     Text ='<%# Eval("Holidaregion") %>' >  
    </asp:Label>

   </ItemTemplate>
</asp:TemplateField>

Updates:

Instead of struggling with inline grid view and server-side code, consider utilizing jQuery to achieve the same result on the client side

Answer №5

Experiment with this code to see how each row can change color based on category or filters applied:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I detect a DOM element mutation based on a CSS selector, and if this is possible, how can it be accomplished?

Imagine there's a website with a specific HTML element. It seems that this element has the same class during the DOMContentLoaded event as it does during the load event. However, after the load event, this class (and possibly the ID and other HTML att ...

Optimizing jQuery Dialog for Different Window Sizes

I am currently developing a responsive website and facing a challenge. I need to implement a popup for window sizes smaller than 480px, but on desktop screens, the content should be visible without being inside the popup. I want to avoid duplicating the co ...

What is the best way to use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...

Utilize styling only when both classes are actively used within media queries or bootstrap

Despite specifying to apply the text-align to 'md-3' instead of 'sm', it still applies when the browser is resized to use the 'sm' style. Simply put, I only want the style to be applied if the media queries interpret my devic ...

Identify the currently active subitem within the item-active class in a PHP carousel slider

I am working on creating an image carousel slider with 4 items and 4 slides each. These images will act as radio buttons, and I want to highlight the slide corresponding to the selected radio button. So, when the carousel loads, the selected slide should b ...

Personalizing the form controls in Bootstrap for selection options

Utilizing Bootstrap's form-control class helps maintain a consistent style for both form input and select option elements. However, when using form-control on select elements, it results in an unsightly drop-down button appearance in Firefox.https://i ...

Optimize flexbox navbar layout by eliminating unnecessary spacing between items

Greetings! As a novice in the world of web development, I must admit that I am facing some difficulties with my homework assignment. Despite my several attempts, I am unable to remove the spacing in the navbar on my university website clone project. It sim ...

Some devices may start the Flutter web page zoomed in by default

Experiencing Zoom Issue on Flutter Web Project: While working on my Flutter web project, I have encountered an issue where the page loads with a zoomed-in view on certain devices. Despite setting the viewport meta tag correctly, the zoom problem persists. ...

I am having trouble displaying the background on my website using css/html

I'm currently working on enhancing my website BJBGaming1.com, and I've encountered an issue with setting a background. Here's the code snippet I have: <!doctype html> <html class="no-js" lang="en"> <head> <meta charset= ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Using jQuery's .get() function to retrieve HTML content is not permissible

I am trying to retrieve the HTML content from another page using the jQuery .get() function as shown below: $.get("chk_vga.aspx", function(data) { alert($('#vga').html()); }); The "chk_vga.aspx" page contains only one value <html> ...

Create a customized HTML popup featuring various packages

I am struggling to create an HTML popup within a React component due to some errors Here is the code snippet: <div> <button class="toggle">Button</button> <div id="link-box"> <ul> ...

Boss declares, "Display the iFrame with no borders visible."

Good day to everyone, I am currently dealing with an issue on the page: It seems to be working perfectly in all of my browsers except for Internet Explorer. Since I don't have IE, I'm having trouble troubleshooting this. My boss mentioned somet ...

jquery slider for inputting phone number on a mobile device

I am currently working on enhancing the user interface by implementing a feature where users can select a mobile number using a slider. The idea is that the user will choose a digit between 0 and 9 using the slider, then confirm their selection by pressing ...

The sidebar in Semantic UI does not have a specified height for the form segment

Need help troubleshooting a button that slides out a vertical sidebar. I want to include a short form for users to input search queries within the sidebar. The issue seems to be with the heights of #search-sidebar and .ui.form.segment. Here is the code s ...

A guide on customizing the appearance of individual items in a vue v-for loop based on specific conditions

I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the ...

Center navigation bar text with the class `.justify-content-center`:

Can someone explain why, when I add the class justify-content-center to my Navbar in Bootstrap, the text remains in the left position? https://i.sstatic.net/8x0Yc.png I came across an instruction in the Bootstrap documentation stating that after adding t ...

Table with Typewriter Style CSS Animation

I came across an interesting typewriter effect implementation using CSS in an article on CSS Tricks I decided to play around with it and see if I could apply it to a hero image, which I found an example of on Codepen However, I noticed that the blinking ...

What are some ways to utilize the pseudo elements ::before and ::after within the Material-UI framework?

Can someone please explain how to use the pseudo-element method in MUI? I couldn't find clear instructions in the documentation, so I decided to post a question here. The docs mention the following about pseudo elements: The box-sizing property is ...

Displaying article title above container with backdrop picture

Currently, I am working on a specific layout design using Bootstrap 5 where I am trying to render a tag outside its original container so that it takes up the full width of the page. My attempts with absolute positioning on the img tag have proven to be ch ...