Mark
Mark

Reputation: 6321

How can you dynamically generate list items to an unordered list in ASP.NET?

I have an error panel that is subbed in to a page if an error goes wrong to gracefully handle and display errors. Currently, I am just appending the error messages to a string and pushing that to a label. If you have multiple errors, this gets messy. Therefore, I'd like to push each error to a list item in a bulleted, unordered list.

How can I dynamically generate, from a vb codebehind file, new list items inside of an undordered list element?

Upvotes: 8

Views: 24050

Answers (2)

Phaedrus
Phaedrus

Reputation: 8421

Why not use a BulletedList control? This control will render an unordered list to the client.

<asp:BulletedList ID="BulletedList" runat="Server" BulletStyle="NotSet">
</asp:BulletedList>

You can then add list items programmatically from code behind like this.

BulletedList.Items.Add("Item1");

You can also accomplish this by adding runat='server' to reference the UL tag server side.

<ul id="uList" runat="server">
</ul>

Then in the code behind use the InnerHtml property to programmatically add LI tags to the contents within the opening and closing UL tags.

uList.InnerHtml += "<li>Item1</li>";

Upvotes: 16

cdeweese
cdeweese

Reputation: 11

You could use a page level variable to hold the errors, like a list or an array. Then just write a method that does something like:

Private Sub WriteErrors()
  lblErrors.txt = "<ul>"
  For Each s as String in _myErrors
   me.lblErrors.Text &= "<li>" & s & "</li>"
  End For
  lblErrors.Text &= "</ul>" 
End Sub

Upvotes: 0

Related Questions