Creating Dynamic Controls on the fly

H

Hayden Kirk

Hi,

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.

Thanks
Hayden
 
M

Mark Rae

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(object sender, System.EventArgs e)
{
LinkButton lnkRemove;
Dictionary<string, byte> dicCart = (Dictionary<string,
byte>)Session["Cart"];

foreach(KeyValuePair<string, byte> kvpItem in dicCart)
{
lnkRemove = new LinkButton();
lnkRemove.EnableViewState = true;
lnkRemove.ID = "lnkRemove_" + kvpItem.Key;
lnkRemove.Text = "X";
lnkRemove.Command += new CommandEventHandler(lnkRemove_Command);
lnkRemove.CommandName = kvpItem.Key;
lnkRemove.Visible = false;
this.pnlCart.Controls.Add(lnkRemove);
}
}

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.
 
H

Hayden Kirk

Sorry, to be a bit more specific,

Reading infro from the eventlog. I now want to create a listbox for each
eventlog I find on the computer. How do I create a bunch of listboxes like
that?

I was going to do:

mylistbox.Name = "listBox" + myEventLog.LogDisplayName;

to be able to reference it or am I way off?
 
G

Guest

Hi,

As long as you know the Log names of the EventLog that you need to read
on your computer, you cld try this:

EventLog evt = new EventLog();
evt.Log = "application";

ListBox lstEvent = new ListBox();
lstEvent.ID = evt.LogDisplayName;

foreach (EventLogEntry evtEntry in evt.Entries)
{
lstEvent.Items.Add(evtEntry.Message);
Page.Form.Controls.Add(lstEvent);
}

This code would be applicable, if you plan on reading one particular log
type, say "application". But then if you plan on doing the same for every log
on the computer, you need to have the log names in some object, cld be string
with a delimiter or a collection object and loop through the object with this
code repeating for every iteration.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top