萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp.net編程 >> Asp.net

Asp.net

本文為大家介紹下如何實現動態生成表,同一列中數據相同的單元格需要合並,具體實現如下,由此需求的朋友可以參考下,希望對大家有所幫助  

業務需要,動態生成表,同一列中數據相同的單元格需要合並。
解決方案,創建Table控件處理類,代碼如下:

復制代碼 代碼如下:
/// <summary>表格控件相關操作類
/// </summary>
public static class aspTable
{
/// <summary>合並行
/// </summary>
/// <remarks>版權信息:http://www.qqextra.com,http://t.qq.com/ls_man,http: //blog.csdn.net/ls_man 2013-06-21 14:20:36</remarks>
/// <param name="tbl">Table</param>
/// <param name="startRow">起始行</param>
/// <param name="endRow">結束行</param>
/// <param name="colIndex">要合並的列索引</param>
public static void SetRowSpan(Table tbl, int startRow, int endRow, int colIndex)
{
int countRowSpan = 0;
int spanRow = startRow;
string spanText = tbl.Rows[startRow].Cells[colIndex].Text;
for (int rowIndex = startRow; rowIndex <= endRow; rowIndex++)
{
string currentText = tbl.Rows[rowIndex].Cells[colIndex].Text;
//內容是否相同
if (currentText == spanText)
{
countRowSpan++;
//移除被合並的單元格
if (rowIndex != spanRow)
{
tbl.Rows[rowIndex].Cells.RemoveAt(colIndex);
}
}
else
{
//合並
tbl.Rows[spanRow].Cells[colIndex].RowSpan = countRowSpan;
//從此行再向下比較(重置)
countRowSpan = 0;
spanRow = rowIndex--;
spanText = currentText;
}
}
//合並最後一項
tbl.Rows[spanRow].Cells[colIndex].RowSpan = countRowSpan;
}
/// <summary>合並行,支持多列
/// </summary>
/// <remarks><SPAN style="FONT-FAMILY: Arial, Helvetica, sans-serif">版權信息:http://www.qqextra.com,http://t.qq.com/ls_man,http: //blog.csdn.net/ls_man</SPAN><SPAN style="FONT-FAMILY: Arial, Helvetica, sans-serif"> 2013-06-21 15:24:34</remarks></SPAN>
/// <param name="tbl">Table</param>
/// <param name="startRow">起始行</param>
/// <param name="endRow">結束行</param>
/// <param name="colIndex">要合並的列索引</param>
public static void SetRowSpans(Table tbl, int startRow, int endRow, params int[] colIndexs)
{
ArrayList al = new ArrayList(colIndexs);
al.Sort();
for (int i = al.Count - 1; i >= 0; i--)
{
SetRowSpan(tbl, startRow, endRow, (int)al[i]);
}
}
}


需要注意的幾點,起始行一般設置為1,因為0是標題行;結束行一般設置為Table的總行數-1即可(最後一行)。

copyright © 萬盛學電腦網 all rights reserved