views:

771

answers:

4

I'll explain what I'm trying to achieve:

I want to have a situation where I can create as many controls as I want by creating them in a loop in the code behind. I can do this while using PHP, by mixing the PHP code and the HTML code. This allows me to generate actual HTML tags dynamically.

In ASP.NET, I haven't found a way to replicate this functionality.

I've thought about using a loop in the code behind on something like the Init() function to create an array of new() objects, setting their attributes and hoping it is passed into the aspx file, but it didn't work.

How do I do this?

+3  A: 

Well, keep in mind there's a difference between Hyperlinks and LinkButtons in ASP.Net

If you just want Hyperlinks, you can create as many as you want by creating a HyperLink object, creating new objects and then adding them to some control's Controls collection like panel or span or something.

LinkButtons are a little different. You have to use a Repeater control if you want to create a link that posts back to the server. (Well, you don't have to but the alternative is a hack job.)

Hyperlinks can be created by using a Repeater control as well and, if possible is the method I would recommend.

Spencer Ruport
+4  A: 
Joel Coehoorn
+2  A: 

If you want to generate controls dynamically & don't need to have those PostBack to the server (i.e. when a control is clicked/changed, it will come back to the same page) - you could use controls in System.Web.UI.HtmlControls namespace.

e.g.

HtmlAnchor link = new HtmlAnchor();
link.href = "www.stackoverflow.com";
Page.Controls.Add(link);

Hope this gives you enough background.

EDIT: You can use the above code in a loop & replace the fixed value with what comes from a database/object.

shahkalpesh
A: 

If you want to creat Dynamically ASP.Net Hyperlink control You can simply do this:

HyperLink hyp = new HyperLink();
    hyp.ID = "hypABD";
    hyp.NavigateUrl = "";
    Page.Controls.Add(hyp);
Muhammad Akhtar