Handling Parent-Child Tables (Page 2)
Introduction
The Database
The Script Basics
The Second Table
Calling the Second Table
Creating the Parent-Child Relationship
Creating the Parent-Child Output
The End
Creating the Parent-Child Relationship
| // Add Parent/Child Relationship dasetForCateg.Relations.Add( "gr_for_out", dasetForCateg.Tables["groups1"].Columns["groid"], dasetForCateg.Tables["forums1"].Columns["groid"] );
|
|
This line creates a Parent-Child relationship between groups1 and forums1. The DataRelationCollection Class is used to handle data relations inside a Dataset. This class is not declared directly but by using the ParentRelations property of a DataTable, or the Relations property of a DataSet, which is what we are doing in this script. Our Relations property is creating a connection between two tables, which allows us to treat dasetForCateg.Relations altogether as if it was DataRelationCollection. This class has Add as one of its methods, and go_for_out is the name of the connection between the DataSet tables groups1 and forums1. Notice that both Colums have groid as an ID, the same ID both tables have in common. And notice that forums1 is the second table, and this makes it the child table. |
Creating the Parent-Child Output
| // Display each Category and Child Products foreach (DataRow drowParent in dasetForCateg.Tables["groups1"].Rows) { lblOutput.Text += "\n<tr>\n<td class='group' colspan='2'>\n<h2>" + drowParent["grname"] + "</h2>\n" + drowParent["grdesc"] + "</td>\n</tr>\n"; foreach (DataRow drowChild in drowParent.GetChildRows( "gr_for_out" )) { lblOutput.Text += "\n<tr>\n<td class='forum'><b>\n" + drowChild["fornme"] + "</b>\n</td>\n<td>\n" + drowChild["fordesc"] + "</td>\n</tr>\n"; } } } </Script>
|
The Tables proterty of the Dataset is followed by another property: Rows, which belongs to the DataTable class. The Tables property can get all the tables inside the DataSet, and the Rows property can get all the rows inside the tables. Our first foreach loop seizes the parent values and stores them in lblOutput as one big string. Notice that we have a second foreach. This one will fetch the childrows contained by the previous DataRow by using the GetChildRows method, where gr_for_out is the name we gave to the data-relation.
|
What remains is simple HTML, except for the asp:Label control whose id is lblOutput (shown above). This control will receive the data from groups and forums. At this point, you should have a good idea of how to create a Parent-Child relationship between two different data-tables.
<head><title>DataRelation.aspx</title>
<style type="text/css" >
h2
{
font-size: 20px;
font-weight: bold;
padding: 2px;
}
.group
{
background: #def;
font-size: 15px;
padding: 10px;
}
.forum
{
background: #fff;
padding: 8px;
}
</style>
</head>
<body>
<table>
<asp:Label
ID="lblOutput"
Runat="Server" />
</table>
</body>
</html>
Bibliography:
Download this tutorial as a PDF file



