user489041
user489041

Reputation: 28294

Use Response.Write() to Create Buttons in ASP.NET

I am trying to create an <asp:Button> in ASP.Net. I have the following code right now:

              <b>Tags:
               <%
                   List<string> tags = GetTags();
                   foreach(string tag in tags)
                   {
                       Response.Write(tag + " ");
                   }
               %>
            <br/>

However, all this does is print the text to the web page. Can I modify this statement in someway to allow me to create buttons with it? Or am I stuck with just text?

Upvotes: 0

Views: 2620

Answers (1)

Icarus
Icarus

Reputation: 63956

You can't create server-side controls in this manner. Simply declare the control in your markup as you would normally do with any html element. For example:

<asp:button id="btnSubmitForm" runat="server" Text="Submit Form" />

If what you want is create simple tags on your markup; do something like this:

<asp:ContentPlaceHolder id="tagPlaceHolder" runat="Server">
</asp:ContentPlaceHolder>

And on the server-side:

List<BrainStorm.Tags> tags = BrainStorm.PostRunner.GetTagsForPost((long)Double.Parse(hiddenField.Value));
foreach(BrainStorm.Tags tag in tags)
{
   Button b = new Button();
   b.Text=tag.Title;
   tagPlaceHolder.Controls.Add(b);
}

This will add a button for every tag you have inside your ContentPlaceHolder

UPDATE:

Inside a repeater...

protected void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) 
{
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
  {
     ContentPlaceHolder placeHolder =  ((ContentPlaceHolder)e.Item.FindControl("tagPlaceHolder"));


  }
}    

Upvotes: 3

Related Questions