Add items to the Bulleted List Control (in the code file)

My next tutorial will be a really short one. But still I have spent a really long time to find what I was looking. Maybe because it was way to easy?

I wanted to generate a BulletedList Web Control, in my code file. Inside a for-loop I wanted to add texts to my list.

[ad#Adsense]

To start, I dropped a PlaceHolder in my file.asp (The html file). Because I like drag and drop, I did it that way! You can find in your toolbox. If you don’t like that, just copy-paste the following text where you would like your BulletedList to appear:
<asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
After that it is time to open the code behind file. In the solution explorer, click at the plus, and then open the default.aspx.cs!

The first thing is to make our Place Holder accessible. Just behind:
public partial class Default: System.Web.UI.Page
But above:
protected void Page_Load(object sender, EventArgs e)
We type this code:
private PlaceHolder PH
{
get
{
return ph1;
}
set
{
ph1 = value;
}
}

We have to create the BulletedList outside the iterator. And inside we can add the items we want to the BulletedList. First my example:
BulletedList BltTest = new BulletedList();
foreach (XmlNode QuestionAnswers in Question)
{
BltTest.Items.Add(new ListItem(QuestionAnswers.InnerText));
}
PH.Controls.Add(BltQTest);

This is the code I did use. But maybe a more generic example helps you with your BulletedList problem!
BulletedList BltTest = new BulletedList();
for (int i = 0; i < 10; i++)
{
BltTest.Items.Add(new ListItem("This is the " + i + "th item"));
}
PH.Controls.Add(BltQTest);

Good luck with your BulletedList!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.