Joonas89
Joonas89

Reputation: 259

adding new LiteralControl to an aspx page, from aspx.cs

So basicly im adding elements to my html, via litterals from the backend. It works great when using it in the asp content placeholders. But i need it to be another specific place on a specific page. Ive tryed making div's with runat="server" But it does not seem to work.. Does anyone have any experience with what i could use? This is part of my code:

foreach (var something in somethingelse)
{
    this.Page.Form.FindControl("ContentPlaceholder1")
        .Controls.Add(
         new LiteralControl("It's a long list, so just typing this.")
    );
}

Upvotes: 0

Views: 977

Answers (2)

Chris W
Chris W

Reputation: 1802

You can use runat="server" on divs. For example:

<div id="myNewDiv" runat="server"></div>

and in the code behind:

myNewDiv.InnerHtml = "Some new text in the div";

If you need to create the divs dynamically you can do the following:

        for (var i = 0; i < 10; i++)
        {
            var ele = new HtmlGenericControl("div")
            {
                InnerHtml = string.Format("new div {0}", i), 
                ID = string.Format("NewDiv_{0}", i)
            };

            Page.Form.FindControl("MainContent").Controls.Add(ele);
        }

You can even push the new divs into an existing div which is anywhere in the ContentPlaceHolder:

        var page = Page.Form.FindControl("MainContent").FindControl("myNewDiv").Controls;
        for (var i = 0; i < 10; i++)
        {
            var ele = new HtmlGenericControl("div")
            {
                InnerHtml = string.Format("new div {0}", i), 
                ID = string.Format("NewDiv_{0}", i)
            };

            page.Add(ele);
        }

Upvotes: 1

Deepan Maheswaran
Deepan Maheswaran

Reputation: 83

Place a HTML tag in source as below

<table>
<tbody>
<-- Your literal control here -->
</tbody>
</table>

and in code behind set literal1.Text ="<tr><td>'"+ Your data here +"'</td></tr>" and it will work

Upvotes: 0

Related Questions