【问题标题】:How to merge gridview rows如何合并gridview行
【发布时间】:2012-05-24 15:22:15
【问题描述】:

我想合并表格,但我不知道如何。我已经尝试了很多次,但仍然无法得到正确的解决方案。现在我的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  |

【问题讨论】:

    标签: c# asp.net gridview merge


    【解决方案1】:

    合并单元格的代码很短:

    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);
    }
    

    【讨论】:

    • 这是一个很好的例子,但是我之前已经试过了,结果和例子不一样。
    • 谢谢!我遇到了与@20151012 类似的问题,这对我来说是这样,除了它仅适用于第一个单元格。所以我取出 for 并将所有对 i 的引用替换为单元格索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2014-11-22
    • 2012-07-29
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多