這幾天做一個(gè)項(xiàng)目有用到表格顯示數(shù)據(jù)的地方,客戶要求重復(fù)的數(shù)據(jù)列需要合并,就總結(jié)了一下GridView 和 Repeater 關(guān)于重復(fù)數(shù)據(jù)合并的方法。

效果圖如下:

GridView :
前臺(tái)代碼 :
<div><asp:GridView ID="gvIncome" runat="server" AutoGenerateColumns="False"><Columns><asp:TemplateField HeaderText="一級(jí)"> <ItemTemplate><asp:Label ID="Label0" runat="server" Text='<%#Eval("aname") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="二級(jí)"><ItemTemplate><asp:Label ID="Label1" runat="server" Text='<%#Eval("bname") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="三級(jí)"><ItemTemplate><asp:Label ID="Label2" runat="server" Text='<%#Eval("cname") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="四級(jí)"><ItemTemplate><asp:Label ID="Label3" runat="server" Text='<%#Eval("dname") %>'></asp:Label></ItemTemplate></asp:TemplateField></Columns></asp:GridView></div>GridView 前臺(tái)代碼<span style="line-height: 1.5; font-family: verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(255, 255, 255);"> </span>
后臺(tái)代碼 :
public void DataBind(){string sql = "select a.aname,b.bname,c.cname ,d.dname from aa as a right join bb as b on a.aid=b.aid right join cc as c on b.bid=c.bid left join dd as d on d.cid=c.cid order by a.aid";SqlDataAdapter sda = new SqlDataAdapter(sql, cn);DataSet ds = new DataSet();sda.Fill(ds);gvIncome.DataSource = ds;gvIncome.DataBind();//MergeRows(gvIncome.HeaderRow, gvIncome.Rows.Count);int colnum = gvIncome.Columns.Count; // 獲取GridView中獲取列數(shù)MergeRows(gvIncome, 4, "Label"); // GridView 要整合的列數(shù) 需要改變的Lable控件}public static void MergeRows(GridView gvw, int colnum, string controlNameo){for (int col = 0; col < colnum; col++) // 遍歷每一列{string controlName = controlNameo + col.ToString(); // 獲取當(dāng)前列需要改變的Lable控件IDfor (int rowIndex = gvw.Rows.Count - 2; rowIndex >= 0; rowIndex--) //GridView中獲取行數(shù) 并遍歷每一行{GridViewRow row = gvw.Rows[rowIndex]; // 獲取當(dāng)前行GridViewRow previousRow = gvw.Rows[rowIndex + 1]; // 獲取當(dāng)前行 的上一行Label row_lbl = row.Cells[col].FindControl(controlName) as Label; //// 獲取當(dāng)前列當(dāng)前行 的 Lable 控件ID 的文本Label previousRow_lbl = previousRow.Cells[col].FindControl(controlName) as Label; //// 獲取當(dāng)前列當(dāng)前行 的上一行 的 Lable控件ID 的文本if (row_lbl != null && previousRow_lbl != null) // 如果當(dāng)前行 和 上一行 要改動(dòng)的 Lable 的ID 的文本不為空{(diào)if (row_lbl.Text == previousRow_lbl.Text) // 如果當(dāng)前行 和 上一行 要改動(dòng)的 Lable 的ID 的文本不為空 且相同{// 當(dāng)前行的當(dāng)前單元格(單元格跨越的行數(shù)。 默認(rèn)值為 0 ) 與下一行的當(dāng)前單元格的跨越行數(shù)相等且小于一 則 返回2 否則讓上一行行的當(dāng)前單元格的跨越行數(shù)+1row.Cells[col].RowSpan = previousRow.Cells[col].RowSpan < 1 ? 2 : previousRow.Cells[col].RowSpan + 1;//并讓上一行的當(dāng)前單元格不顯示previousRow.Cells[col].Visible = false;}}}}}GridView 后臺(tái)代碼
新聞熱點(diǎn)
疑難解答
圖片精選