如何合并gridview行

时间:2012-05-17 02:26:59

标签: c# asp.net gridview merge

我想合并表但我不知道如何。我已经尝试了很多次但仍然无法获得正确的解决方案。现在我的gridview是这样的:

Data 1  |  Data 1  |  Data 1  |  Data 1
Data 1  |  Data 1  |  Data 1  |  Data 1
Data 2  |  Data 2  |  Data 2  |  Data 2
Data 2  |  Data 2  |  Data 2  |  Data 2

我希望gridview像这样:

Data 1   |   Data 1   |   Data 1  |   Data 1
         |   Data 1   |   Data 1  |
Data 2   |   Data 2   |   Data 2  |   Data 2
         |   Data 2   |   Data 2  |

1 个答案:

答案 0 :(得分:3)

合并单元格的代码非常短:

public class GridDecorator
{
    public static void MergeRows(GridView gridView)
    {
        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow row = gridView.Rows[rowIndex];
            GridViewRow previousRow = gridView.Rows[rowIndex + 1];

            for (int i = 0; i < row.Cells.Count; i++)
            {
                if (row.Cells[i].Text == previousRow.Cells[i].Text)
                {
                    row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : 
                                           previousRow.Cells[i].RowSpan + 1;
                    previousRow.Cells[i].Visible = false;
                }
            }
        }
    }
}

最后一个操作是为GridView添加一个OnPreRender事件处理程序:

protected void gridView_PreRender(object sender, EventArgs e)
{
    GridDecorator.MergeRows(gridView);
}