老D

我是一个粗人
  博客园  :: 首页  :: 新随笔  :: 管理

合并 GridView 的单元格

Posted on 2008-09-03 11:38  老D  阅读(623)  评论(0编辑  收藏  举报

     在用GridView展示数据的时候需要把相同的列的单元格横或坚合并在一起(如下图所示),以前做这样的图一直用Repeater,但Repeater分页没有用GridView快,直接点分页就可以自动完成(人懒),现在换成用GridView做,没想到更简单

实现代码:

//在RowCreated事件中添加多一个表头列

   protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {

           //删除默认的2个cell,以便下面自己添加的列跟竖跨本默认列
            e.Row.Cells.RemoveAt(1);
            GridViewRow rowHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
            rowHeader.BackColor = System.Drawing.Color.White;
            rowHeader.Font.Bold = true;

            TableCellCollection cells = e.Row.Cells;
            TableCell headerCell = new TableCell();
            headerCell.HorizontalAlign = HorizontalAlign.Center;
            headerCell.Text = "姓名";
            rowHeader.Cells.Add(headerCell);

            headerCell = new TableCell();
            headerCell.HorizontalAlign = HorizontalAlign.Center;
            headerCell.Text = "学期";

            //竖跨两列
            headerCell.RowSpan = 2;
            rowHeader.Cells.Add(headerCell);

            headerCell = new TableCell();
            headerCell.Text = "学生成绩";

            //学生成绩列横跨剩下几个单元格
            headerCell.ColumnSpan = cells.Count - 1;
            headerCell.HorizontalAlign = HorizontalAlign.Center;

            rowHeader.Cells.Add(headerCell);
            rowHeader.Visible = true;
            GridView1.Controls[0].Controls.AddAt(0, rowHeader);
        }
    }

 

//在DataBound事件中把相同的名字合并

    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; )
        {
            string nowValue = GridView1.Rows[i].Cells[0].Text;
            int j = i + 1;
            for (; j < GridView1.Rows.Count; j++)
            {
                if (nowValue == GridView1.Rows[j].Cells[0].Text)
                    GridView1.Rows[j].Cells.RemoveAt(0);
                else
                    break;
            }
            if ((j - i) > 1) //如果只有一列就不用RowSpan了,虽然用了没影响,但还是多生成一点html代码
            {
                GridView1.Rows[i].Cells[0].RowSpan = j - i;
            }
            i = j;
        }

    }