動態建立 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);
tbl.Rows.Count - 1。Cell.Text,若 Cell 含控制項需自行擷取值。ColumnSpan(水平合併)。GridView 的 RowDataBound 事件中自動套用。