Search code examples
c#asp.netanchorserver-sidecode-behind

how add server side Anchor to a div form code behind?


plz see the aspx below first :

<div id="divFilesBody">
              <div class="divFilesBody_Row">
                <%= Files %>
                <a id="MyAnchor1" runat="server" OnServerClick="AnchorForDwonload_Click">Server Side Anchor 1</a>
            </div>

MyAnchor1 Serverside click event works perfect!
i want to make something like that from code behind :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using FileExplorer.Classes;

namespace FileExplorer.en
{
    public partial class Download : System.Web.UI.Page
    {
        public string Files = "";
        protected void Page_Load(object sender, EventArgs e)
        {
...
            foreach (FileInfo f in dir.GetFiles("*.*"))
            {
                Files += "<a class='MyAnchor2' runat='server' OnServerClick='AnchorForDwonload_Click'>";
                Files += "Server Side Anchor 2";
                Files += "</a>";
            }
        Files += "<a id='MyAnchor3' runat='server' OnServerClick='AnchorForDwonload_Click'>";
        Files += "Server Side Anchor 3";
        Files += "</a>";
        }

        protected void AnchorForDwonload_Click(object sender, EventArgs e)
        {
            Response.Write("Server Side Anchor Works");
        }

    }
}

but MyAnchor2 does not work after firing page load...
how can i solve this issue?

EDIT
i added MyAnchor3 After comment (An Anchor With ID) -> still does not work

the output html is like this :

        <a id='MyAnchor3' runat='server' OnServerClick='AnchorForDwonload_Click'>
        Server Side Anchor 3
       </a>

thanks in advance


Solution

  • That is not the right way to create dynamic controls in ASP.NET. You can use LinkButton controls to achieve this:

    You should be doing something like this instead:

    Markup:

    <asp:Panel ID="pnlFilesBody" runat="server">
        <!-- resolves to a DIV -->
    </asp:Panel>
    

    Code-behind:

    protected override void OnInit(EventArgs e)  
    {   
        //create controls at every page load and assign the same ids to the controls
        //to preserve click events
    
        foreach (FileInfo f in dir.GetFiles("*.*"))  
        { 
            //create a new linkbutton
            LinkButton btn = new LinkButton();
            btn .ID = String.Format("lnk_{0}", pnlFilesBody.Controls.Count);
            btn.Click += new EventHandler(btn_Click);
            btn.Text = String.Format("Server Side Anchor {0}", pnlFilesBody.Controls.Count);
    
            //add the linkbutton to the files body panel
            pnlFilesBody.Controls.Add(btn);
        }
    }
    
    protected void btn_Click(object sender, EventArgs e)
    {
        //put your click event logic here
    }