Link to home
Start Free TrialLog in
Avatar of pointeman
pointemanFlag for United States of America

asked on

GridView Cell Color Red If Text Empty?

The following code changes the entire column to Red, however I would like to just change Only cells with empty text.

Q. How can I change Only certain Cells Red and not the entire column?

    protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if(e.Row.Cells[7].Text.Contains(""))
                e.Row.Cells[7].BackColor = System.Drawing.Color.Red;
        }
    }
Avatar of himanshut
himanshut
Flag of Australia image

maybe coz your that column would be empty that's why the condition is true to get the cell color Red
ASKER CERTIFIED SOLUTION
Avatar of MajorBigDeal
MajorBigDeal
Flag of United States of America 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 pointeman

ASKER

Okay, here's how it's done in RowDataBound (similar to MajorBigDeal).

I can now read text of both:
asp:BoundField
asp:TemplateField (Text='<%# Bind("FirstName") %>'>).


    protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
            foreach (GridViewRow row in gridView1.Rows)
            {                              
                if(row.Cells[6].Text == "10")
                row.Cells[6].BackColor = System.Drawing.Color.Red;

                if(((Label)row.FindControl("label1")).Text == "Jim")
                    ((Label)row.FindControl("label1")).BackColor = System.Drawing.Color.Green; //right-next to cell[6].

            }    
    }
New Problem:
  1. asp:CommandField won't 'fire', throws error:
        "Object reference not set to an instance of an object."
   
However, asp:ButtonField works fine.
Yes but it doesn't make sense to put that in row data bound because you are iterating the entire grid for every row. For example, if your grid has 100 rows , your loop will run 10000 times.  I guess it doesn;t really matter but I think it would be better in the page load.  

I want to help with your new problem, but there isn't enough info,  Also, if you open a new question for that, you'll probably get more responses since experts are always jumping on new questions.
I'll give you points because your solution works, but not in RowDataBound.