【问题标题】:GridView with merged cells合并单元格的 GridView
【发布时间】:2013-04-15 09:43:39
【问题描述】:

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

来自数据库的原始数据格式如下:

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

【问题讨论】:

    标签: c# asp.net gridview sqldatasource


    【解决方案1】:

    您必须使用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

    【讨论】:

    • 感谢您的帮助,此代码完全符合我的要求。
    • 我还需要问一件事,有没有办法限制这个单元格合并修复列而不是网格视图的所有列。例如,在我提供的示例表中,我们是否应该实施任何限制,以便单元格合并不会应用于备注字段列。
    • 是的,你可以,你只需要知道你想限制它的适当索引,并且必须适当地对其进行编程。
    • @Freelancer 您的示例适用于边界字段,但我在 gridview 中定义了模板,并且此代码无法使用它。你能帮我对模板字段做同样的事情吗?
    • @Nikhil 可能会有所帮助stackoverflow.com/questions/13177139/…
    【解决方案2】:

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

    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”

    【讨论】:

    • 这个解决方案对我来说非常完美,将 3 行合并为 1 列用于第一列
    猜你喜欢
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    相关资源
    最近更新 更多