0

I have a site (build with asp .net) and I want to add to it some text and pictures during runtime (I don't know the amount before).
After the user chooses the parameters, he clicks a button which invokes the following code (in the .cs file):

foreach (var car in cars)
{
  Label lbl = new Label ();
  form1.Controls.Add(lbl);
  lbl.Text = car.name;
  Image myImage = new Image ();
  form1.Controls.Add(myImage);
  myImage.ImageUrl = car.imageURL;

}

but when I run the code, I don't see the controls on the page. am I missing something?
Thanks!

2
  • At what point in the page life-cycle are you running that code? Commented Jul 4, 2011 at 14:59
  • At the Postback event handling stage. Commented Jul 4, 2011 at 15:09

5 Answers 5

0

You have to assign the control to the form BEFORE setting it's properties.

For example:

foreach (var car in cars){  
  Label lbl = new Label ();
  form1.Controls.Add(lbl); // Create and immediately assign

  lbl.Text = car.name;  // now you can set some properties

  Image myImage = new Image ();
  form1.Controls.Add(myImage);  // Ditto

  myImage.ImageUrl = car.imageURL;
}

UPDATE:

I just created a brand new web application project with a page that only had a button on it; it worked as expected. I suggest you have something else going on. See below:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

    </div>
    </form>
</body>
</html>

and the code behind:

namespace WebApplication1 {
    public partial class _Default : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {

        }

        protected void Button1_Click(object sender, EventArgs e) {
            for (Int32 i = 0; i < 10; i++) {
                Label lbl = new Label();
                form1.Controls.Add(lbl);
                lbl.Text = "HAHAHAHAH";
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is not true, it doesn't matter whether you set the properties first or after adding the control. See my sample, which works for both literal controls.
@M4N: Actually it is true. Viewstate doesn't start tracking changes until the control is added to the hierarchy. So, if you set a custom value (like text) before adding it to the hierarchy then viewstate won't be able to detet that you changed it when it's rehydrated. For this example, it shouldn't matter. However, for textboxes etc it will. We ran into this dynamically creating a Table and adding lots of textboxes and dropdowns to it. Nothing worked right until we did the property assignment AFTER associating the new controls with the container.
I agree regarding ViewState - but as you said, for this example it's not required.
@M4N: rats, caught in my own logic loop.. ;)
0

Try adding a placeholder control onto your form. Then instead of calling Form1.Controls.Add(....) use PlaceHolder1.Controls.Add(.....)

1 Comment

@menacheb, the placeholder1 concept should work..we used it many times to load user controls at runtime and adding them to place holders
0

When you create dynamic controls on a Web Form, the controls must be created and added to the controls collection either in the OnInit or in the Page_Load events.

Please refer this question in order to solve your issue.

Comments

0

You can try what AndyPeacock says but looking at your code I think what you need to research into is actually Repeaters and other databound controls like DataListView.

Here's a quick example of how you could implement this with a Repeater:

In your ASPX file:

<asp:Repeater ID="RepCars" runat="server">
    <ItemTemplate>
        <%# Eval("name") %>
        <img src='<% Eval("imageURL") %>' alt="" />
    </ItemTemplate>
</asp:Repeater>

And on your .CS part, probably in Page_Load:

   RepCarImages.DataSource = cars;
   RepCarImages.DataBind();

Have a look at http://www.w3schools.com/ASPNET/aspnet_repeater.asp

Comments

0

Not an answer, but the following stripped-down sample works for me:

<%@ Page Language="C#" AutoEventWireup="true" %>
<html>
<head runat="server"></head>
<body>
    <form id="form1" runat="server">

        <script runat="server">
        protected void Button1_Click(object sender, EventArgs e)
        {
            var lit = new Literal();
            Controls.Add(lit);
            Controls.Add(new Literal() { Text = "aaaa" });
            lit.Text = "some text -- ";
        }
        </script>

    <asp:Button ID="Button1" runat="server" Text="Button"
      onclick="Button1_Click" />
    </form>
</body>
</html>

So it seems you have not posted enough information to answer your question?

Comments

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.