We help IT Professionals succeed at work.

Gridview RowDataBound change cell font color based on other cells text

doramail05
doramail05 asked
on
Medium Priority
12,725 Views
Last Modified: 2012-06-21
trying to change the colour of 'actualtime' column into green if the 3rd cell is 'ontime'
but it still remain unchanged.
protected void gvStudentAttendance_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[3].Text == "ontime")
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Green;
            }
        }
    }

<asp:GridView ID="gvStudentAttendance" runat="server" GridLines="Both" 
        AutoGenerateColumns="false" onrowdatabound="gvStudentAttendance_RowDataBound">
        <Columns>
            <asp:BoundField HeaderText="Lesson" DataField="LessonCode" HeaderStyle-HorizontalAlign="Left" />
             <asp:BoundField HeaderText="ActualTime" DataField="ActualTime" HeaderStyle-HorizontalAlign="Left" />
             <asp:BoundField HeaderText="Lab" DataField="Lab" HeaderStyle-HorizontalAlign="Left" />
             <asp:BoundField HeaderText="Attendance Status" DataField="StudentAtt" HeaderStyle-HorizontalAlign="Left" Visible="false" />
             <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID="lblstudentatt" runat="server" Text='<%# Eval("StudentAtt") %>' Visible="false" />
                </ItemTemplate>
             </asp:TemplateField>
        
        </Columns>
   
   </asp:GridView>

Open in new window

Comment
Watch Question

Paul JacksonSoftware Engineer
CERTIFIED EXPERT
Top Expert 2011

Commented:
Have you stepped through the code in debug, is it actually getting to the line?

Author

Commented:
after removing
if (e.Row.RowType == DataControlRowType.DataRow)
it stepped through the line

but the thing is e.Row.Cells[3].Text  is actually the header text of 3rd cell, instead of getting the row item,
then tried something like e.Row.DataItem[3].Text, but it doesnt seem like it,

Commented:
Because you have the BoundField visibility set to false it is not rendering on the page and therefore displays "string.empty" as its value when you are trying to evaluate against it. The same would happen if you were trying to read from your label control in the template.

Instead read from the DataRowView and you can get at the value you want to evaluate against(see code):
protected void gvStudentAttendance_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView dRow = (DataRowView)e.Row.DataItem;

        if (dRow.Row["StudentAtt"].ToString() == "ontime")
        {
            e.Row.Cells[1].ForeColor = System.Drawing.Color.Green;
        }
    }
}

Open in new window

Author

Commented:
on line
DataRowView dRow = (DataRowView)e.Row.DataItem;

getting -- >
Unable to cast object of type 'StudentAttendance' to type 'System.Data.DataRowView'.

Commented:
Well shucks. Not really sure what that's about... I'm gonna guess:

You're binding to a custom object?? Either your making a mistake or it has something to do with the datasource method you are using. What are you binding to specifically and how are you doing it?

In my test I made a simple sqlTable reflecting your column names and bound this to a SqlDataSource. I run this with your exact code and get the following to work fine.

See Sample code I used (and ran)
<form id="form1" runat="server">
	<asp:GridView ID="gvStudentAttendance" runat="server" GridLines="Both" AutoGenerateColumns="false"
		DataSourceID="SqlDev"
		OnRowDataBound="gvStudentAttendance_RowDataBound">
		<Columns>
			<asp:BoundField HeaderText="Lesson" DataField="LessonCode" HeaderStyle-HorizontalAlign="Left" />
			<asp:BoundField HeaderText="ActualTime" DataField="ActualTime" HeaderStyle-HorizontalAlign="Left" />
			<asp:BoundField HeaderText="Lab" DataField="Lab" HeaderStyle-HorizontalAlign="Left" />
			<asp:BoundField HeaderText="Attendance Status" DataField="StudentAtt" HeaderStyle-HorizontalAlign="Left"
				Visible="false" />
			<asp:TemplateField>
				<ItemTemplate>
					<asp:Label ID="lblstudentatt" runat="server" Text='<%# Eval("StudentAtt") %>' Visible="false" />
				</ItemTemplate>
			</asp:TemplateField>
		</Columns>
	</asp:GridView>
	<asp:SqlDataSource ID="SqlDev" runat="server" ConnectionString="<%$ ConnectionStrings:DevTest %>"
	 SelectCommand="SELECT * FROM StudentAttendance"></asp:SqlDataSource>
	</form>


protected void gvStudentAttendance_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView dRow = (DataRowView)e.Row.DataItem;

        if (dRow.Row["StudentAtt"].ToString() == "ontime")
        {
            e.Row.Cells[1].ForeColor = System.Drawing.Color.Green;
        }
    }
}

Open in new window

DevSql.jpg

Author

Commented:
it is getting from a list of StudentAttendance class that fetch stored procedure data and put into the list,

and the list is then
 List<StudentAttendance> list_stuatt = new List<StudentAttendance>();

            list_stuatt = StudentAttendance.GetStudentAttendanceBY_Module_Intake_SP("Module01", "Dec2011");

            if (list_stuatt.Count > 0)
            {
                gvStudentAttendance.DataSource = list_stuatt;
                gvStudentAttendance.DataBind();
            }
#region Get Student Attendance (module, intake) From Stored Procedure 

    public static List<StudentAttendance> GetStudentAttendanceBY_Module_Intake_SP(string strModule, string strIntake)
    {
        string strConnString = connstring.getIDashString();

        List<StudentAttendance> listtemp_studentatt = new List<StudentAttendance>();

        using (SqlConnection myConnection = new SqlConnection(strConnString))
        {
            SqlCommand myCommand = new SqlCommand("spStudentAttendance", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters.AddWithValue("@module", strModule);
            myCommand.Parameters.AddWithValue("@intake", strIntake);
            myConnection.Open();
            using (SqlDataReader myReader = myCommand.ExecuteReader())
            {
                if (myReader.HasRows)
                {
                    while (myReader.Read())
                    {
                        listtemp_studentatt.Add(FillDataRecord_GetStudentAttendance(myReader));
                    }
                }
                myReader.Close();
            }
        }
        return listtemp_studentatt;
    }

Open in new window

Commented:
What if we try standing the problem on its side for a minute...

Lets grab the evaluation from the label instead and see if that gets you there. This works for me, and disproves my previous thought that the visibility would affect things on the label. (See Code)

It also occurs to me that in your code (because of the ?? difference) you may just be doing a bad evaluation here:
if (e.Row.Cells[3].Text == "ontime")

All it would take is the text in your db to be "Ontime" and this would not function.

If you check what value you were getting here it would be helpful. Maybe add:
string test = e.Row.Cells[3].Text;
And put a breakpoint on it, OR:
Response.Write(e.Row.Cells[3].Text);

When I checked this is was empty. Then when I turned on the visibility it had the correct value.

if (e.Row.RowType == DataControlRowType.DataRow)
{
    Label lb = (Label)e.Row.Cells[4].Controls[1];

    if (lb.Text == "ontime")
    {
        e.Row.Cells[1].ForeColor = System.Drawing.Color.Green;
    }
}

Open in new window

Commented:
Alright you test that stuff I just mentioned and I'll make a custom object :)
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.