Covert
Covert

Reputation: 491

Why foreach loop fails at last row of gridview?

I have put a code to COLOR the background of GRIDVIEW Cell# 14 if cell's text != "nbsp;" and it does work except for the last row. It doesn't color the last row even it isn't equal to "nbsp;"

protected void grdviewCases_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow) 
        {
            foreach (GridViewRow gr in grdviewCases.Rows)
            {
                if (gr.Cells[14].Text != " ")
                {
                    gr.Cells[14].BackColor = Color.Red; ;
                    gr.Cells[14].ForeColor = Color.WhiteSmoke;
                }
            }
        }
    }

Upvotes: 4

Views: 1374

Answers (1)

haraman
haraman

Reputation: 2742

You need not loop rows in RowDataBound event, you may just use e object to reference each row

protected void grdviewCases_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow) 
        {
            if (e.Row.Cells[14].Text != " ")
            {
                e.Row.Cells[14].BackColor = Color.Red; ;
                e.Row.Cells[14].ForeColor = Color.WhiteSmoke;
            }
        }
    }

For more details check system.web.ui.webcontrols.gridview.rowdatabound

Upvotes: 6

Related Questions