一直以來,客戶需要在WEB上面顯示嵌套的數(shù)據(jù)頁面,如下圖所示:
而我們的項目全部統(tǒng)一采用DataGrid來進行數(shù)據(jù)的綁定顯示.對于這種嵌套數(shù)據(jù)的顯示,我一直頭疼.在網(wǎng)上搜了N種方法:采用嵌套DataGrid...手動在數(shù)據(jù)綁定的時候進行一些額外操作分割單元格.....全部都麻煩得要死.今天總算在CodeProject上面找到一種方便點的方法:采用Repeater來解決這個問題.
首先,來看下我的DataGrid中列的html代碼:
<asp:BoundColumn Visible="False" DataField="ID"></asp:BoundColumn>
<asp:BoundColumn DataField="OrganName" HeaderText="部門名稱"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="員工">
<ItemTemplate>
<FONT face="宋體">
<asp:Repeater id="Repeater1" runat="server" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("parentchild") %>'>
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem,"[/"EmployeeName/"]")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater></FONT>
</ItemTemplate>
</asp:TemplateColumn>
其中的ID列表示機構的ID,用來和員工信息中的機構ID進行"關聯(lián)".
再來看關鍵代碼
DataSet ds = new DataSet();
DataTable dtOrgan = new DataTable();
dtOrgan.Columns.Add("ID",typeof(string));
dtOrgan.Columns.Add("OrganName",typeof(string));
...
/*...往機構表中灌數(shù)據(jù)...*/
ds.Tables.Add(dtOrgan);
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("OrganID",typeof(string));
dtEmployee.Columns.Add("EmployeeName",typeof(string));
...
/*...往員工表中灌數(shù)據(jù)...*/
ds.Tables.Add(dtEmployee);
ds.Relations.Add("parentchild",ds.Tables[0].Columns["ID"],ds.Tables[1].Columns["OrganID"]);
dgList.DataSource = ds.Tables[0].DefaultView;
dgList.DataBind();
最主要的就是利用了DataSet的Relations的屬性,通過屬性來將父子表關聯(lián)起來,然后進行數(shù)據(jù)的綁定.最后,在WEB上運行出來的效果如下所示: