萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 動態產生 Table 並自動合併相同資料儲存格

需求

動態建立 Table 控制項,針對指定欄位將連續相同文字的儲存格垂直合併(RowSpan)。

通用合併類別

public static class AspTableHelper
{
    /// <summary>單欄合併</summary>
    public static void SetRowSpan(Table tbl, int startRow, int endRow, int colIndex)
    {
        int count = 0;
        int spanStart = startRow;
        string spanText = tbl.Rows[startRow].Cells[colIndex].Text;

        for (int r = startRow; r <= endRow; r++)
        {
            string currText = tbl.Rows[r].Cells[colIndex].Text;
            if (currText == spanText)
            {
                count++;
                if (r != spanStart)
                    tbl.Rows[r].Cells.RemoveAt(colIndex); // 移除被合併的 Cell
            }
            else
            {
                tbl.Rows[spanStart].Cells[colIndex].RowSpan = count;
                count = 0;
                spanStart = r;
                spanText = currText;
                r--; // 重新評估目前列
            }
        }
        // 最後一組
        tbl.Rows[spanStart].Cells[colIndex].RowSpan = count;
    }

    /// <summary>多欄合併(由右至左處理,避免索引位移)</summary>
    public static void SetRowSpans(Table tbl, int startRow, int endRow, params int[] colIndexes)
    {
        Array.Sort(colIndexes);
        for (int i = colIndexes.Length - 1; i >= 0; i--)
            SetRowSpan(tbl, startRow, endRow, colIndexes[i]);
    }
}

使用範例

Table tbl = new Table();
// ... 動態產生 Rows & Cells ...

// 假設第 0 列為標題,資料列 1~10,需合併第 0、2 欄
AspTableHelper.SetRowSpans(tbl, 1, 10, 0, 2);

關鍵細節

  • 從右往左處理多欄:避免移除 Cell 後導致索引錯位。
  • 起始列通常為 1:第 0 列常為標題列不參與合併。
  • 結束列:tbl.Rows.Count - 1。
  • 文字比較:預設使用 Cell.Text,若 Cell 含控制項需自行擷取值。

擴充建議

  • 支援 ColumnSpan(水平合併)。
  • 支援依多欄位組合判斷是否合併(群組合併)。
  • 整合至自訂 GridView 的 RowDataBound 事件中自動套用。
copyright © 萬盛學電腦網 all rights reserved