GridView裡合併相同內容的儲存格,是常有的需求。
以下的範例可選擇多個需要合併的欄位:(在PreRender事件裡處理)
protected void gv_PreRender(object sender, EventArgs e)
{
int[] mergeColumns = { 0 }; //要合併的欄位-編號(款)
foreach (int mergeColumn in mergeColumns)
{
int i = 1;
// 取得來源GridView
GridView gv = (GridView)sender;
if (gv!= null)
{
foreach (GridViewRow row in gv.Rows)
{
row.Cells[mergeColumn].RowSpan = 0;
if (row.RowIndex != 0)
{
if (row.Cells[mergeColumn].Text.Trim() == gv.Rows[(row.RowIndex - i)].Cells[mergeColumn].Text.Trim())
{
gv.Rows[(row.RowIndex - i)].Cells[mergeColumn].RowSpan += 1;
row.Cells[mergeColumn].Visible = false;
i += 1;
}
else
{
row.Cells[mergeColumn].RowSpan += 1;
i = 1;
}
}
else
{
row.Cells[mergeColumn].RowSpan = 1;
}
}
}
}
}