"Hayden Kirk kirk mobilepc.co.nz> " <hayden <dot@wrote in message
news:eF******** ******@TK2MSFTN GP04.phx.gbl...
I'm having a bit of trouble. I want to create a number of controls on the
fly. They are all the same control type. How is the best way to do this?
I have a name I can assign to them so I know how to reference them, but I
don't know how to create them.
This is a piece of code I use in conjunction with a shopping cart. It
dynamically creates one LinkButton control for every item in the cart:
private void Page_Init(objec t sender, System.EventArg s e)
{
LinkButton lnkRemove;
Dictionary<stri ng, bytedicCart = (Dictionary<str ing,
byte>)Session["Cart"];
foreach(KeyValu ePair<string, bytekvpItem in dicCart)
{
lnkRemove = new LinkButton();
lnkRemove.Enabl eViewState = true;
lnkRemove.ID = "lnkRemove_ " + kvpItem.Key;
lnkRemove.Text = "X";
lnkRemove.Comma nd += new CommandEventHan dler(lnkRemove_ Command);
lnkRemove.Comma ndName = kvpItem.Key;
lnkRemove.Visib le = false;
this.pnlCart.Co ntrols.Add(lnkR emove);
}
}
Notice that the code is in Page_Init - this is important, otherwise the
controls' events won't get wired up properly...
When the controls are originally created, they are added to an <asp:Panel>
for use later in the page creation cycle.