answerSeeker
answerSeeker

Reputation: 2772

How to dynamically add items to bulleted list from code-behind in the master page

My master page has a bulleted list defined as below:

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
   <ul class="nav navbar-nav">
        <li>
            <asp:LinkButton ID="btnHome" runat="server" class="active" CausesValidation="false">Home </asp:LinkButton>
        </li>
        <li>
            <asp:BulletedList ID="headerMenu" DisplayMode="LinkButton" class="nav navbar-nav" CausesValidation="false" runat="server">
            </asp:BulletedList>
        </li>
   </ul>
</div>

Now I am trying to access it from a content page (child of master) "_Default.cs" and add some items to it. Below is what I have already tried but it doesn't work as I'm getting error 'System.Web.UI.WebControls.BulletedList' does not allow child controls.

public partial class _Default : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            LinkButton mybl = new LinkButton();
            mybl.Text = "my item";
            BulletedList Bl = (BulletedList)Master.FindControl("headerMenu");
            if (Bl != null) {
                Bl.Controls.Add(mybl);
            }

        }
    }

}

How can I change the master page dynamically and modify the BulletedList from my child content page?

Upvotes: 2

Views: 1783

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

BulletedList does not allow child controls occurred because BulletedList doesn't support template controls which usually set with Controls.Add() method. Here is a remark from BulletedList.Controls property:

The Controls property is inherited from the Control class and is not applicable to the BulletedList control.

Instead, you need to add ListItem items into ListItemCollection using Items.Add() method, assumed the BulletedList exists inside master page:

if (!IsPostBack) {
    headerMenu.Items.Add(new ListItem("my item"));
}

If you want item text together with URL, put the URL as second parameter of ListItem:

if (!IsPostBack) {
    headerMenu.Items.Add(new ListItem("my item", "http://path/to/url"));
}

Reference: BulletedList Class

Upvotes: 2

Related Questions