Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating HTML tags dynamically in code-behind

Tags:

c#

asp.net

How can I add HTML tags to aspx file from the code-behind?

When I create new object

Graph MyChart = new Graph();

I want it add a tag for this object

<Graph id="MyChart" runat="server" Height="500px"></Graph>

What is the solution for that?

like image 702
Hzyf Avatar asked Jan 24 '26 10:01

Hzyf


1 Answers

Not sure if we are talking about a .NET control or HTML on the fly, I give examples of both.

This will add it to the end of the page, but I suggest you use a PlaceHolder to control where it gets added:

Graph MyChart = new Graph();
MyChart.ID = "MyChart";
Page.Controls.Add(MyChart);

//genericcontrol example
HtmlGenericControl NewControl = new HtmlGenericControl("graph");

// Set the properties of the new HtmlGenericControl control.
NewControl.ID = "MyGraph";
Page.Controls.Add(NewControl);

PlaceHolder example:

 <form id="form1" runat="server">
      <h3>PlaceHolder Example</h3>
      <asp:PlaceHolder id="PlaceHolder1" 
           runat="server"/>
   </form>

  protected void Page_Load(Object sender, EventArgs e)
  {
     Graph MyChart = new Graph();
     MyChart.ID = "MyChart";
     PlaceHolder1.Controls.Add(MyChart);

    //genericcontrol example
    HtmlGenericControl NewControl = new HtmlGenericControl("graph");

    // Set the properties of the new HtmlGenericControl control.
    NewControl.ID = "MyGraph";
    PlaceHolder1.Controls.Add(NewControl);

  }
like image 141
rick schott Avatar answered Jan 25 '26 22:01

rick schott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!