HOW TO ADD A DIV CONTAINS ASP LABEL FROM CODE BEHIND IN ASP.NET

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
C#  ASP.Net 
 1223  View(s)
Ratings:
Rate this:

I tried to add a div which contains an asp:Label on a button click event.
The following code which I used. CODE

string htmlString = "<div><asp:Label ID=\"l1\" runat=\"server\" Text=\"WELCOME\"></asp:Label></div>";

Panel1.Controls.Add(new LiteralControl(htmlString));

But I am not able to view that particular div.
Please try to solve me this.

Thanks in advance.

  1. Mark Devid

    Post:102

    Points:714
    Re: How to Add a div contains asp Label from code behind in asp.net

    Adding the markup for a server control like that will not process the server control but simply will put that markup in the produced HTML

    You can use a HTmlGenericControl to do that

    using System.Web.UI.HtmlControls;

     

    Label lbl = new Label();

    lbl.Text = "WELCOME";

     

    HtmlGenericControl div = new HtmlGenericControl("div");

     

    div.Controls.Add(lbl);

    Panel1.Controls.Add(div);

    To add a DataList inside the div you can do the following

    DataList dl = new DataList();

    //Init your DataList here

    dl.DataSource = dt; // `dt` is a DataTable with my data

    dl.DataBind()

     

    HtmlGenericControl div = new HtmlGenericControl("div");

     

    div.Controls.Add(dl);

    Panel1.Controls.Add(div);

     

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!