C#GridView垂直和水平交替显示背景颜色

时间:2013-02-22 18:30:05

标签: c# asp.net gridview

我正在开发一个ASP.NET Web应用程序,我希望像国际象棋(垂直和水平)交替使用gridview单元格的颜色。颜色为黄色和黑色。

2 个答案:

答案 0 :(得分:3)

您可能希望使用GridView的RowDataBound事件,如下所示:

   <asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False" 
         DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">

   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
   {
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;

        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            TableCell Cell = e.Row.Cells[i];

            // if both row and column are odd, color then black
            // if both row and column are even, color then yellow
            if (((e.Row.RowIndex % 2 == 1) && (i % 2 == 1)) ||
                ((e.Row.RowIndex % 2 == 0) && (i % 2 == 0)))
                Cell.BackColor = Color.Black;
            else
                Cell.BackColor = Color.Yellow;
        }
    }

答案 1 :(得分:1)

设置ItemStyle和AlternatingItemStyle属性,并指定BackGroundColor和Color属性。这些控制着这些颜色。