Often we use nested GridView controls, so that individual rows in the master GridView can display a nested GridView in one of its columns. This is especially useful to show master/details relationships. However sometimes we might want to show the nested GridView only for the selected row. This post discusses one way to do it.
Understanding of the GridView control.
Understanding of TemplateField class.
Understanding of SqlDataSource class.
If you are looking to understand how to create nested GridView controls, there is an excellent article on MSDN titled: Walkthrough: Creating a Nested GridView Control
Listed below is the source code for my aspx page. I've kept only the essential parts of the code:
1: <asp:SqlDataSource ID="masterDataSource" .../>
2: <asp:SqlDataSource ID="nestedDataSource" ... />
3: <asp:GridView ID="masterGrid" OnSelectedIndexChanged="masterGrid_SelectedIndexChanged" ...>
5: <asp:BoundField ... />
6: <asp:BoundField ... />
9: <asp:GridView ID="nestedGrid" DataSourceID="nestedDataSource" Visible="false">
11: <asp:BoundField ... />
Line 1: SqlDataSource called masterDataSource which will be used to populate the master GridView (masterGrid, line 3)
Line 2: SqlDataSource called nestedDataSource which will be used to populate the nested GridView (nestedGrid, line 9)
Line 3: Master GridView called masterGrid. Uses masterDataSource as the data source. Specifies masterGrid_SelectedIndexChanged as the method handler for SelectedIndexChanged event.
Line 9: Nested GridView called nestedGrid. Uses masterDataSource as the data source. Insert as a TemplateField.
Listed below is the source code for the masterGrid_SelectedIndexChanged event:
Line 3-6: I hide all the nestedGrid controls.
Line 11: For only the selected row I show the nestedGrid. It was as simple as that!.