为什么foreach循环在gridview的最后一行失败?

时间:2015-10-10 06:22:38

标签: c# asp.net visual-studio gridview

如果单元格的文字!=" nbsp;"除最后一行外,它确实有效。它没有为最后一行着色,即使它不等于" 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;
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:5)

你不需要在RowDataBound事件中循环行,你可以只使用e对象来引用每一行

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;
            }
        }
    }

有关详细信息,请查看system.web.ui.webcontrols.gridview.rowdatabound