how to add a div to container div in c# code behind

前端 未结 5 1569
慢半拍i
慢半拍i 2020-12-17 09:18

ASP.NET, C#

As the title suggests I was wondering if anyone knew how to programatically (c# code behind file) add a div to another a container div (in the aspx page)

5条回答
  •  北海茫月
    2020-12-17 09:52

    This may be a very old question but I would like to add my solution for helping:

    First, to the "div" you already have in your page (the one you want to add another "div" to) give the runat="server" property so you can access it from code behind, it would look like this:

    Then in your Page_Load() method add the following:

    protected void Page_Load(object sender, EventArgs e)
    {
       //We create our new div
       System.Web.UI.HtmlControls.HtmlGenericControl newDiv = 
         new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
       newDiv.ID = "newSuperDIV"; //<---Give and ID to the div, very important!
       newDiv.Style.Value = "background-color:white; height:61%;"; //<---Add some style as example
       newDiv.Attributes.Add("class", "amazingCssClass"); //<---Apply a css class if wanted
       superDiv.Controls.Add(newDiv); //<---Add the new div to our already existing div
    }
    

    Genearte your div directly inside the Page_Load function so it will assure that exists after any postback, avoid generating it inside code blocks like (!IsPostBack){} otherwise it will not exist in your page.

提交回复
热议问题