前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form runat="server"> <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("id") %></td> <td runat="server" id="td1"><%#Eval("modeljsName")%></td> <td runat="server" id="td2"><%#Eval("modelName")%></td> <td><%#Eval("modelHref")%></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </form> </body> </html>
后台代码:
using ClassLibrary1; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { BindData(); } private void BindData() {this.rptList.DataSource = null;//传入数据源 this.rptList.DataBind(); List<string> list = new List<string>(); list.Add("td1"); list.Add("td2"); IfTable.MergeCell(list,rptList); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace ClassLibrary1 { /// <summary> /// Table合并单元格方法 /// </summary> public class IfTable { /// <summary> /// 循环Table行数 /// </summary> /// <param name="list">获取检索字段集合</param> public static void MergeCell(List<string> list, Repeater repeater) { for (int i = repeater.Items.Count - 1; i > 0; i--) { for (int j = 0; j < list.Count; j++) { MergeCellSet(list[j], i, repeater); } } } /// <summary> /// 合并单元格方法 /// </summary> /// <param name="tdIdName1">跨行字段ID名称</param> /// <param name="i">当前行数</param> private static void MergeCellSet(string tbstr, int i, Repeater repeater) { HtmlTableCell cellPrev = repeater.Items[i - 1].FindControl(tbstr) as HtmlTableCell; HtmlTableCell cell = repeater.Items[i].FindControl(tbstr) 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; } } } }