1

我正在尝试根据数据键为我的 gridview 背景行颜色着色。我想要的是每组数据键名称以灰色着色,然后是下一个颜色为白色,然后是下一个颜色为灰色等。因此根据不同的数据键名称交替。这是我下面的代码。有人能帮我吗?

protected void grdContents_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //Default values
    string strPreviousDataKeyValue = "";
    Color RowColor = Color.grey;
    foreach (GridViewRow row in grdContents.Rows)
    {
        if (!strPreviousDataKeyValue.Equals(grdContents.DataKeys[row.RowIndex].Value.ToString()))
        {
            row.BackColor = RowColor;
            strPreviousDataKeyValue = grdContents.DataKeys[row.RowIndex].Value.ToString();
        }
    }
}
4

1 回答 1

3

RowDataBound对 中的每一行执行GridView。所以你的foreach循环非常多余。您还必须检查正确的RowType = DataRow.

这应该有效:

protected void grdContents_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.RowIndex == 0)
            e.Row.BackColor = Color.Gray;
        else
        {
            var thisKey = grdContents.DataKeys[e.Row.RowIndex].Value;
            var prevKey = grdContents.DataKeys[e.Row.RowIndex - 1].Value;
            var prevRow = grdContents.Rows[e.Row.RowIndex - 1];
            if (thisKey.Equals(prevKey))
                e.Row.BackColor = prevRow.BackColor;
            else
                e.Row.BackColor = prevRow.BackColor == Color.Gray ? Color.White : Color.Gray;
        }
    }
}
于 2013-05-28T13:48:37.890 回答