我正在尝试根据datakey为gridview backgroud rowcolor着色。我想要的是每个数据键名称组以灰色着色,然后下一个颜色为白色,然后是下一个颜色灰色等。因此根据不同的数据键名称交替。这是我下面的代码。有人能帮我吗?
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();
}
}
}
答案 0 :(得分: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;
}
}
}