Dynamically Adding An Accordion Pane (C#)
The Accordion control in the AJAX Control Toolkit provides multiple panes and allows the user to display one of them at a time. Panels are usually declared within the page itself, but server-side code can be used to achieve the same result.
Overview
The Accordion control in the AJAX Control Toolkit provides multiple panes and allows the user to display one of them at a time. Panels are usually declared within the page itself, but server-side code can be used to achieve the same result.
Steps
The Accordion control exposes all important properties to server-side code. Among other things, the Panes
property grants access to the collection of panes that make up the Accordion. Every pane there is of type AccordionPane
. It is therefore trivial to create such a pane:
[!code-csharpMain]
1: AccordionPane ap1 = new AccordionPane();
The HeaderContainer
property of AccordionPane
provides access to the ASP.NET controls within the header section of the pane; the ContentContainer
property of AccordionPane
does the same for the content section of the pane. This allows ASP.NET code to add content to the panes:
[!code-csharpMain]
1: ap1.HeaderContainer.Controls.Add(new LiteralControl("Using Code"));
2: ap1.ContentContainer.Controls.Add(new
3: LiteralControl("Adding panes using code is really flexible."));
Finally, the pane(s) must be added to the Panes
collection of the Accordion:
[!code-csharpMain]
1: acc1.Panes.Add(ap1);
Here is a complete server-side code that adds two panes to an Accordion control:
[!code-aspxMain]
1: <script runat="server">
2: void Page_Load()
3: {
4: if (!Page.IsPostBack)
5: {
6: AccordionPane ap1 = new AccordionPane();
7: ap1.HeaderContainer.Controls.Add(new LiteralControl("Using Markup"));
8: ap1.ContentContainer.Controls.Add(new
9: LiteralControl("Adding panes using markup is really simple."));
10: AccordionPane ap2 = new AccordionPane();
11: ap2.HeaderContainer.Controls.Add(new LiteralControl("Using Code"));
12: ap2.ContentContainer.Controls.Add(new
13: LiteralControl("Adding panes using code is really flexible."));
14: acc1.Panes.Add(ap1);
15: acc1.Panes.Add(ap2);
16: }
17: }
18: </script>
The only missing element is the Accordion itself, which depends on the presence of the ASP.NET ScriptManager
control:
[!code-aspxMain]
1: <form id="form1" runat="server">
2: <asp:ScriptManager ID="asm" runat="server" />
3: <div>
4: <ajaxToolkit:Accordion ID="acc1" runat="server"
5: HeaderCssClass="header" ContentCssClass="content"
6: Width="300px" FadeTransitions="true">
7: </ajaxToolkit:Accordion>
8: </div>
9: </form>
To finish the example, the two CSS classes referenced in the Accordion control provide style information for the browser:
[!code-cssMain]
1: <style type="text/css">
2: .header {background-color: blue;}
3: .content {border: solid;}
4: </style>
The data in the accordion was dynamically added by server-side code (Click to view full-size image)
|