带有合并单元格的GridView

时间:2013-04-22 13:10:32

标签: c# asp.net gridview sqldatasource

我需要在网格视图中显示数据,并为某些列合并行。请帮我准备以下定义格式的网格视图: enter image description here

原始数据来自数据库,格式如下: enter image description here

请帮助我找到动态有效地完成此任务的最佳方法。

2 个答案:

答案 0 :(得分:19)

您必须使用RowSpan

请参阅以下代码:

protected void GridView1_DataBound1(object sender, EventArgs e)
{
  for (int rowIndex = GridView1.Rows.Count - 2;
                                     rowIndex >= 0; rowIndex--)
  {
    GridViewRow gvRow = GridView1.Rows[rowIndex];
    GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
    for (int cellCount = 0; cellCount < gvRow.Cells.Count;
                                                  cellCount++)
    {
     if (gvRow.Cells[cellCount].Text ==
                            gvPreviousRow.Cells[cellCount].Text)
     {
       if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
       {
         gvRow.Cells[cellCount].RowSpan = 2;
       }
       else
       {
        gvRow.Cells[cellCount].RowSpan =
            gvPreviousRow.Cells[cellCount].RowSpan + 1;
       }
       gvPreviousRow.Cells[cellCount].Visible = false;
    }
   }
}

<强>全球化志愿服务青年:

https://sites.google.com/site/learning6329/asp-net/gridview-merge-cells

图示示例为问题:

http://marss.co.ua/MergingCellsInGridView.aspx

答案 1 :(得分:1)

合并第一列的行单元的最简单方法如下。请注意,For Loop总是反向迭代。

protected void GridView1_DataBound(object sender, EventArgs e)
    {
        int RowSpan = 2;
        for (int i = GridView1.Rows.Count-2; i >=0 ;i-- )
        {
            GridViewRow currRow = GridView1.Rows[i];
            GridViewRow prevRow = GridView1.Rows[i+1];
            if (currRow.Cells[0].Text == prevRow.Cells[0].Text)
            {
                currRow.Cells[0].RowSpan = RowSpan;
                prevRow.Cells[0].Visible = false;
                RowSpan += 1;
            }
            else
                RowSpan = 2;
        }
    }

如果你想类似地合并所有列的行单元格,你可以在上面写的外部forloop中使用另一个“forloop”