How to Add a div contains asp Label from code behind in asp.net

Total Post:183

Points:1285
C#  ASP.Net 
 1587  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. 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);

     

      Modified On Apr-07-2018 06:27:37 AM

Answer