GridView、Repeater合并单元格可以参考http://www.cnblogs.com/zhmore/archive/2009/04/22/1440979.html,但是原文例子是合并一列的单元格。
现在有2列需要分别合并单元格,如下所示,“类型”和“操作”当有相同的值时要分别合并:
可以在原来的代码上稍做改动,前台代码如下:
<asp:Repeater runat="server" ID="rptList"> <HeaderTemplate> <table width="100%" border="1" cellpadding="4" cellspacing="0" bgcolor="#464646" style="border-collapse:collapse; padding:0; margin:0"> <tr bgcolor="#eeeeee"> <td>序号</td> <td>类型</td> <td>操作</td> <td>编号</td> </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="#ffffff"> <td><%# Eval("rn") %></td> <td runat="server" id="td1"><%#Eval("Col1")%></td> <td runat="server" id="td2"><%#Eval("Col2")%></td> <td><%#Eval("Col3")%></td> <td><%#Eval("Col4")%></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater>
后台代码如下:
private void BindData() { rptList.DataSource = null; //这里为数据源,省略... rptList.DataBind(); MergeCell("td1", "td2"); } private void MergeCell(string tdIdName1, string tdIdName2) { for (int i = rptList.Items.Count - 1; i > 0; i--) { MergeCellSet(tdIdName1, tdIdName2, i); } } private void MergeCellSet(string tdIdName1, string tdIdName2, int i) { HtmlTableCell cellPrev = rptList.Items[i - 1].FindControl(tdIdName1) as HtmlTableCell; HtmlTableCell cell = rptList.Items[i].FindControl(tdIdName1) as HtmlTableCell; cell.RowSpan = (cell.RowSpan == -1) ? 1 : cell.RowSpan; cellPrev.RowSpan = (cellPrev.RowSpan == -1) ? 1 : cellPrev.RowSpan; if (cell.InnerText == cellPrev.InnerText) { cell.Visible = false; cellPrev.RowSpan += cell.RowSpan; //关键代码,再判断执行第2列的合并单元格方法 if (tdIdName2 != "") MergeCellSet(tdIdName2, "", i); } }