Code Sample for
Nested DataLists (C# Version)
Sometimes, we need to nest data - say for instance - List the Categories, and under each Category, list the Products for that particular Category.
This sample uses the SQL Managed Provider to show exactly that, using the Categories and Products tables from the NorthWind Database.
As usual, just copy this code directly into a new page, change the database/connection information to match your system, and run it from your own computer.
You can read a Tutorial about this code here.
Thanks to Mike Houston for this code sample
http://www.nexus6studio.com
See this code in VB.Net
See the Code Below:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<HTML>
<HEAD>
<title>Nested Datalists Using C#</title>
<script language=C# runat=server>
void Page_Load(object sender, System.EventArgs e)
{
string strConn = "Server=YourServer;uid=yourUID;pwd=YourPWD;database=Northwind";
string MySQL = "Select CategoryID, CategoryName from Categories";
SqlConnection MyConn = new SqlConnection(strConn);
DataSet ds = new DataSet();
SqlDataAdapter Cmd = new SqlDataAdapter(MySQL,MyConn);
Cmd.Fill(ds,"Categories");
SqlDataAdapter Cmd2 = new SqlDataAdapter("select * from Products",MyConn);
Cmd2.Fill(ds,"Products");
ds.Relations.Add("myrelation", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Products"].Columns["CategoryID"]);
dlCategories.DataSource = ds.Tables["Categories"].DefaultView;
DataBind();
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:DataList runat="server"
Id="dlCategories"
GridLines="Both"
Bordercolor="black"
cellpadding="3"
cellspacing="0"
Headerstyle-BackColor="#DDDDDD"
Headerstyle-Forecolor="#777777"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="14"
Headerstyle-Font-Bold="true"
Font-Name="Arial"
Font-Bold="true"
Font-Italic="true"
Font-Size="11"
ForeColor="Red"
RepeatColumns="1">
<HeaderTemplate>
Categories & Products
</HeaderTemplate>
<ItemTemplate><%# DataBinder.Eval(Container, "DataItem.CategoryName") %>
<br>
<asp:DataList runat="server"
Id="ChildDataList"
GridLines="None"
Bordercolor="black"
cellpadding="3"
cellspacing="0"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="8"
Font-Name="Arial"
Font-Size="8"
datasource='<%# DataBinder.Eval(Container, "DataItem.myrelation") %>'
RepeatColumns="3">
<ItemTemplate>
<%# DataBinder.Eval(Container, "DataItem.ProductName") %>
</ItemTemplate>
</ASP:DataList>
</ItemTemplate>
</asp:DataList>
</form>
</body>
</HTML>