Editing Nested DataGrids in ASP.NET, Page 3
If you have your heart set on using a DataList with a nested DataGrid, my good friend Joe Shook demonstrated a functional way to do this as well.
Define a Web Form with a DataList. In that form, implement your editing events. Each time the DataList.ItemCreated event fires, the ItemCreated event will send an argument containing a DataListItem. The DataListItem contains the dynamically created UserControl. Using the event argument, call e.Item.Find("uc1"), where uc1 is your UserControl's ID, to obtain a reference to the template-created UserControl. If the Find returns the UserControl, request the DataGrid on that UserControl and manually re-associate your edit event handlers with the DataGrid by calling AddHandler.
In this alternative example, your UserControl and DataGrid's events actually reside in the page containing the DataList. I am not a big fan of that part of the solution, but it does seem to work. A modest revision would entail moving the edit event handlers to the UserControl and binding the DataGrid's event properties to the UserControl's event handlers using AddHandler. This revision should work and now your behavior travels with your component, the UserControl.
There are so many things I like about programming in .NET that the few things that seem out of whack don't bother me too much. From my own experience, conversations, and newsgroups, it appears that nesting a DataGrid in a DataList doesn't work quite the way one would expect. Perhaps this is by design or is a bug; we may never know.
Through experimentation, it appears that a nested DataGrid's edit events aren't restored when the DataGrid is nested in a DataList. In this article, Part 3 of 3, I demonstrated a workaround for the nonexistent edit behavior that excludes the DataList from the equation, requiring you to load a UserControl containing a DataGrid for each object in the master data source—this is the data used as the DataList's data source. As an alternative, you can use the DataList with a nested DataGrid, but you will have to manually find the dynamically created DataGrids defined in the DataList's templates and re-associate the DataGrid event handlers in the DataList's ItemCreated event. The later approach, while not shown here, has been demonstrated to work.
I suspect from conversations I have had that Microsoft is aware of this relatively minor problem and a more permanent solution will be forthcoming.
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. Paul Kimmel is available to help design and build your .NET solutions and can be contacted at email@example.com.