Accordion动态添加AccordionPane
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ Control Language="C#" AutoEventWireup="true" Codebehind="Menu.ascx.cs" Inherits="Web.Controls.Menu" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<div style="width: 100%; text-align: left;">
<ajaxToolkit:Accordion ID="MyAccordion" runat="Server" SelectedIndex="0" HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent"
AutoSize="None" FadeTransitions="true" TransitionDuration="250" FramesPerSecond="40"
RequireOpenedPane="false" SuppressHeaderPostbacks="true">
<Panes>
</Panes>
<HeaderTemplate>
<div style="width: 150px; height: 35px; color: White; background-image: url('<%=ResolveClientUrl("~/Images") %>/Slice1.png');">
<div style="padding-top: 10px; padding-left:10px; font-weight:bold; font-size:12px;">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</div>
</HeaderTemplate>
<ContentTemplate>
<div style="width: 150px; height: auto; line-height: 25px; background-color: #748CCF;
text-align: left;">
<div style="margin-left: 20px; color: White;">
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
</div>
</div>
</ContentTemplate>
</ajaxToolkit:Accordion>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</div>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Web.Controls
{
public partial class Menu : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
CreatMenu();
}
void CreatMenu()
{
int count = 1;
foreach (SiteMapNode group in SiteMap.RootNode.ChildNodes)
{
AjaxControlToolkit.AccordionPane ap = new AjaxControlToolkit.AccordionPane();
ap.Header = MyAccordion.HeaderTemplate;
ap.Content = MyAccordion.ContentTemplate;
HyperLink hl = new HyperLink();
hl.Text = group.Title;
hl.Target = group.Url;
foreach (Control c in ap.HeaderContainer.Controls)
{
if (c.GetType().Name == "PlaceHolder")
{
c.Controls.Add(hl);
break;
}
}
foreach (SiteMapNode child in group.ChildNodes)
{
HyperLink hl2 = new HyperLink();
hl2.Text = child.Title;
hl2.Target = child.Url;
foreach (Control c in ap.ContentContainer.Controls)
{
if (c.GetType().Name == "PlaceHolder")
{
c.Controls.Add(hl2);
break;
}
}
}
count++;
MyAccordion.Panes.Add(ap);
}
}
}
}