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";
}
}
}
}