4

How can I populate a bootstrap dropdown from codebehind? Right now I am trying this:

    HtmlGenericControl li;

    for (int x = 3; x <= 10; x++)
    {
        li = new HtmlGenericControl("li");
        li.Attributes.Add("class", "myItemClass");
        li.InnerText = "Item " + x;

        myList.Controls.Add(li);
    }

This does add the items but it completely loses the bootstrap design on the <li>-items. Also, how do I know which value is DataTextField and which is DataValueField?

Dropdown html:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" id="myList" runat="server">

  </ul>
</div>
3
  • It looks like you are following the example at getbootstrap.com/components/#dropdowns - only you are just adding <li> items, whereas they are using <li><a/></li> Commented Feb 16, 2015 at 15:14
  • I had a hunch that this was the problem, but my questions still stands since I dont know how to add <li><a/></li> items Commented Feb 16, 2015 at 15:17
  • probably something like li.Children.Add(new GenericControl("a")); Commented Feb 16, 2015 at 15:19

1 Answer 1

4

It would probably be easier for you to add them using a literal, like this:

Dropdown.aspx:

<div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
        Dropdown
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" id="myList" runat="server">
        <asp:Literal runat="server" id="litDropDown"></asp:Literal>
    </ul>
</div>

Dropdown.aspx.cs:

for (int x=3; x<10;x++)
{
    string liText = "";

    liText = liText + "<li role=\"presentation\">";
    liText = liText + "<a role=\"menuitem\" tabindex=\"-1\" href=\"#\">";
    liText = liText + "Item " + x;
    liText = liText + "</a></li>";

    litDropDown.Text = litDropDown.Text + liText;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm, thanks! PS: If I want to add DataTextField and DataValueField. How can I do this using this method?
@iQue - Can you provide an example of what you are trying to acheive?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.