Tutorial :How to place a hyperlink field in a web page at runtime?


I am trying to display contents of a folder in a hyperlink. I am using masterpage also. The hyperlinks are not shown into the content page. what to do for that?

I know in windows forms we can use like TextBox.Location=new Point(100,100);

But how to do in web page...please anybody suggest me..

my coding in page_load is

protected void Page_Load(object sender, EventArgs e)  {      DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/ProjectsUpload"));      int i = 0;      foreach (FileInfo fi in di.GetFiles())      {          HyperLink HL = new HyperLink();          HL.ID = "HyperLink" + i++;          HL.Text = fi.Name;          HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;          Page.Controls.Add(HL);          Page.Controls.Add(new LiteralControl("<br/>"));      }  }  


You can't add it directly to Page.Controls. You have to add it to the ContentPlaceHolder on the page.


Instead of dynamically creating controls, which is rather messy and error-prone, have you considered using an asp:Repeater control and binding the files directly to it? Something like:

<asp:Repeater ID="RepeaterFiles" runat="server">      <ItemTemplate>          <asp:HyperLink runat="server" Text='<%# Container.DataItem %>'               NavigateUrl='<%# String.Format("downloading.aspx?file={0}", Container.DataItem)%>' />          <br />      </ItemTemplate>  </asp:Repeater>  

and in code behind:

DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/ProjectsUpload"));  RepeaterFiles.DataSource = di.GetFiles();  RepeaterFiles.DataBind();  

That way you can use declarative mark-up to control layout and keep the logic in your code-behind.


Put a PlaceHolder control on your page:

<asp:PlaceHolder runat="server" ID="ph" />  

In your code behind write like:

HyperLink HL = new HyperLink();  HL.ID = "HyperLink" + i++;  HL.Text = fi.Name;  HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;  ph.Controls.Add(HL);  ph.Controls.Add(new Literal { Text = "<br/>"});  

I'm making use of the newly C# 3 feature on that last line to set the Text property.


Have you used the debugger to step through the loop to verify that it processes at least one file?

Instead of adding the links to Page.Controls, you could put a list control on the page, and then add each link within a list item. Then you'd know precisely where on the page they should appear.


Create a Panel or a Label in the Page's Content area, and add your HyperLinks into the Controls collection of the Panel.

(Stepping through the code to check whether the IIS App actually enumerates any files in the directory would help too.)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »