Managing Complex Layout and Nesting DataGrids in ASP.NET, Page 2
Putting a DataGrid in a DataList's Item Template
Another approach is to repeat an entire block of data. For example, if we define a relationship where the Customer has a list of contact information, for each customer we may want to show both the customer information and the nested, repeating contact information. Nesting a DataGrid inside of a DataList is a relatively low-impact way to achieve this result.
Figure 2 shows the results of nesting a DataGrid within our DataList. Before we talk about how to create this effect, let's take a moment to clear up some details. The first detail is that the DataGrid border was left in place to make it clear where the DataGrid was located. The second detail is that all of the contact information was intentionally initialized to the same value (e.g. Number=411 and Description=Information); displaying other values is simply a matter of modifying the relevant fields with code or user input. Finally, I used a strongly typed collection of customer objects and each Customer object contained a list of contact information. One could use any data structure that can be used as a DataSource for the DataList and DataGrid, such as a DataSet.
Click here for a larger image.
Figure 2: The nested DataGrid in the DataList. The DataGrid border was left in for clarity.
We already know how to create the ID, First Name, Last Name, and Picture columns; I re-used the code provided in Listing 1. The new part is the nested contact information. Let's talk about a convenient means of creating this effect.
To create the nested effect, do this:
- Drop a DataGrid onto the Web Page containing the HTML table/DataList, but not intermixed with those controls.
- Use the Properties window to modify the properties of the DataGrid. For example, set AutoGenerateColumns to False and define the (DataBindings) property as shown in Figure 3. (Basically, the DataSource property was set to DataBinder.Eval(Container.DataItem, "ContactInformationList") where the Container.DataItem will be a Customer object.)
- Then, switch to the HTML view and add a new column to the ItemTemplate and SelectedItemTemplate using the data cell tag-pair <td></td>.
- In the HTML, find the definition of the DataGrid—it will begin with the tag <DataGrid> and end with a matching </DataGrid>. Paste the DataGrid definition in between the new <td></td> pair defined in the ItemTemplate and SelectedItemTemplate.
- Add the code that supplies the DataSource and calls DataBind in the code-behind, and you're ready to run the example.
Figure 3: Use the DataBindings dialog to define the DataSource for the DataGrid.
For your perusal, the ItemTemplate containing the DataGrid—now playing the role of template—is provided in Listing 2 and the complete implementation of the Customer and ContactInformation is provided without comment in Listing 3.
Listing 2: The revised ItemTemplate, including the nested DataGrid definition (highlighted), section from Listing 1.
1: <ItemTemplate> 2: <tr height="30px"> 3: <td> 4: <asp:LinkButton id="Linkbutton2" CommandName="Select" runat="server"> 5: <%# DataBinder.Eval(Container.DataItem, "ID") %> </asp:LinkButton></td> 6: <td> 7: <asp:Label id="Label6" runat="server"> 8: <%# DataBinder.Eval(Container.DataItem, "FirstName") %> </asp:Label></td> 9: <td> 10: <asp:Label id="Label7" runat="server"> 11: <%# DataBinder.Eval(Container.DataItem, "LastName") %> </asp:Label></td> 12: <td> 13: <asp:Label id="Label8" runat="server"> 14: <%# DataBinder.Eval(Container.DataItem, "Email") %> </asp:Label></td> 15: <td>
16: <asp:DataGrid id=DataGrid1 17: DataSource= 18: '<%# DataBinder.Eval(Container.DataItem, "ContactInformationList") %>' 19: runat="server" AutoGenerateColumns="False"> 20: <Columns> 21: <asp:BoundColumn DataField="ID" ReadOnly="True" 22: HeaderText="ID"></asp:BoundColumn> 23: <asp:BoundColumn DataField="Number" HeaderText="Number"> </asp:BoundColumn> 24: <asp:BoundColumn DataField="Description" 25: HeaderText="Description"></asp:BoundColumn> 26: </Columns> 27: </asp:DataGrid>
Listing 3: The strongly typed Customer and ContactInformation collections used for the samples.
Public Class CustomerList Inherits CollectionBase Public Shared Function GetCustomerList() As CustomerList Dim obj As CustomerList = New CustomerList obj.Add(New Customer(1, "Paul", "Kimmel", _ "email@example.com", _ "~/Images/PaulKimmel.jpg")) obj.Add(New Customer(2, "Brad", "Jones", "")) obj.Add(New Customer(3, "Robert", "Golieb", "")) obj.Add(New Customer(4, "Geoff", "Caylor", "")) obj.Add(New Customer(5, "Joe 'Bilbo'", "Shook", "")) Return obj End Function Default Public Property Item(ByVal Index As Integer) As Customer Get Return CType(List(Index), Customer) End Get Set(ByVal Value As Customer) List(Index) = Value End Set End Property Public Function Add(ByVal Value As Customer) As Integer Return List.Add(Value) End Function End Class Public Class Customer Private FID As Integer Private FFirstName As String Private FLastName As String Private FEmail As String Private FPicture As String Private FContactInformationList As ContactInformationList Public Sub New() End Sub Public Sub New(ByVal ID As Integer, ByVal FirstName As String, _ ByVal LastName As String, ByVal EMail As String, _ Optional ByVal Picture As String = "~/Images/Unavailable.jpg") FID = ID FFirstName = FirstName FLastName = LastName FEmail = EMail FPicture = Picture FContactInformationList = _ ContactInformationList.GetContactInformationList(ID) End Sub Public Property ID() As Integer Get Return FID End Get Set(ByVal Value As Integer) FID = Value End Set End Property Public Property FirstName() As String Get Return FFirstName End Get Set(ByVal Value As String) FFirstName = Value End Set End Property Public Property LastName() As String Get Return FLastName End Get Set(ByVal Value As String) FLastName = Value End Set End Property Public Property Email() As String Get Return FEmail End Get Set(ByVal Value As String) FEmail = Value End Set End Property Public Property Picture() As String Get Return FPicture End Get Set(ByVal Value As String) FPicture = Value End Set End Property Public ReadOnly Property ContactInformationList() _ As ContactInformationList Get Return FContactInformationList End Get End Property End Class Public Class ContactInformationList Inherits CollectionBase Public Shared Function GetContactInformationList(ByVal ID _ As Integer) As ContactInformationList Dim obj As ContactInformationList = New ContactInformationList obj.Add(New ContactInformation(ID, "411", "Information")) obj.Add(New ContactInformation(ID, "www.yahoo.com", _ "People Search")) Return obj End Function Default Public Property Item(ByVal Index As Integer) _ As ContactInformation Get Return CType(List(Index), ContactInformation) End Get Set(ByVal Value As ContactInformation) List(Index) = Value End Set End Property Public Function Add(ByVal Value As ContactInformation) As Integer Return List.Add(Value) End Function End Class Public Class ContactInformation Private FID As Integer Private FNumber As String Private FDescription As String Public Sub New(ByVal ID As Integer, ByVal Number As String, _ ByVal Description As String) FID = ID FNumber = Number FDescription = Description End Sub Public Property ID() As Integer Get Return FID End Get Set(ByVal Value As Integer) FID = Value End Set End Property Public Property Number() As String Get Return FNumber End Get Set(ByVal Value As String) FNumber = Value End Set End Property Public Property Description() As String Get Return FDescription End Get Set(ByVal Value As String) FDescription = Value End Set End Property End Class
It is worth noting that if we don't use the HTML table interspersed with the DataList, much, if not all, of the editing of the DataList and DataGrid can occur visually. As with a lot of programming, unfortunately, the most advanced things still have to be done by hand.
Templating with a UserControl
An excellent way to separate tasks and make managing the code-behind easier is to heavily employ UserControls. For example, what if we wanted to programmatically interact with the nested DataGrid? Unfortunately, DataGrid1 doesn't actually exist in the code-behind. When we cut the DataGrid from the page and pasted it in the template, we have a template definition for the grid, but each row creates a grid dynamically. Getting to those templated, dynamic grids is messy and time consuming. We have to implement events for the DataList and invoke FindControl or rely on the literal column position. This results in complicated code, dynamic binding of events, and slower performance; calling FindControl incurs some overhead.
There is a better way. If we place the DataGrid on its own UserControl, we can modify the definition of the DataGrid and add extra code at any time. By placing the UserControl containing the DataGrid in the DataList, we get the same visual effect as if we placed the grid in the DataList directly, yet any modifications to the separate UserControl-with-DataGrid are easier to effect and show up immediately in the DataList. The net benefit is that our DataList's HTML is much simpler, the same visual result can be affected, the code-behind for the DataGrid can be implemented at design time much more easily, and the UserControl can be used in other contexts. The DataList, then, simply devolves to a mechanism for repeating the template section.
There is a drawback using the DataList with a nested DataGrid approach: editing nested DataGrid seems to be broken. If you invoke an edit behavior on a DataGrid, your code will receive the Edit behavior but not subsequent events, such as Update. This is a problem. Fortunately, there is a solution and the clue resides in the role that our DataList has been relegated too in the last paragraph.
In this article, I demonstrated how to control layout by using an HTML table across DataList template regions. I also demonstrated how to nest a DataGrid within a DataList. Many of us are aware that displaying data using nested DataLists and DataGrids work fine, but editing behavior seems to break down. In the third installment of this article, I will help you solve that problem.
In Part III, I will demonstrate how to implement a repeated DataGrid behavior that will permit you to add, edit, update, and delete data. The approach demonstrated requires a bit of cleverness, but will work sufficiently until the DataGrid and DataList support complex nesting in conjunction with editing behavior.
About the Author
Paul Kimmel is a software architect, writer, and columnist for codeguru.com. Look for his recent book, Visual Basic .NET Power Coding from Addison-Wesley on Amazon.com. Paul Kimmel is available to help design and build your .NET solutions and can be contacted at firstname.lastname@example.org.
Page 2 of 2