Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
                }
            }
        }
    }
like image 215
Covert Avatar asked Oct 19 '25 08:10

Covert


1 Answers

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

like image 185
haraman Avatar answered Oct 22 '25 00:10

haraman