Dynamically adding List Items to an Unordered List Item using C#.net

In one of my project i am working, i got a requirement to add List items to Unordered List Items programmatically to create dynamic tab structure. I'll close this in a short answer by explaining you the below code snippet.

The standard UL tag should set to runat=server in C#.Net so that we can access it from code behind and add the LI tags dynamically to it.

HTML Markup:
  <ul class="respond" id="feedbackTab" runat="server"></ul>

C#.Net Code Behind:

  //adding text to the tab using InnerText
  HtmlGenericControl li = new HtmlGenericControl("li");
  li.InnerText = "My Tab1"; 

  (or)

  li.InnerHtml = "<div>My Tab 1</div>";
  feedbackTab.Controls.Add(li);

Instead of adding plain text to the tab we can also add anchor tag which navigates to another page after clicking on that tab.

  HtmlGenericControl li = new HtmlGenericControl("li");
  feedbackTab.Controls.Add(li);
  HtmlGenericControl anchor = new HtmlGenericControl("a");
  anchor.Attributes.Add("href", "aboutme.aspx");
  anchor.InnerText = "Tab Text";
  li.Controls.Add(anchor);

Hope this information is useful and here ends yours search.
Dynamically adding List Items to an Unordered List Item using C#.net Dynamically adding List Items to an Unordered List Item using C#.net Reviewed by Sudheer Gangumolu on September 13, 2014 Rating: 5

No comments: