Home / ASP.NET Wiki / HTML / Page.ParseControl

Page.ParseControl

 Rate It (2)

If you want to parse a html string at runtime with asp.net control in it you can use the method ParseControl, for example if you have a html fragment like this:

  <table>
      <tr>
          <td>Name</td>
      </tr>
      <tr>
          <td><asp:TextBox id="name" runat="server" /></td>
      </tr>
  </table>


Now if you want to parse this string at runtime into a Control object, you can do this with the ParseControl method from the TemplateControl class, the ParseControl methods can be accessed from the Page instance, like this:

string html = "<table><tr><td>Name</td></tr><tr><td><asp:TextBox id=\"name\" runat=\"server\" /></td></tr>b</table>"

Control ctrl = Page.ParseControl(html);

somePlaceHolder.Controls.Add(ctrl);


After the html has been parsed the control can be added to for example a placeholder.

Revision number 2, Thursday, December 04, 2008 4:34:31 PM by syed.tayyab.ali

Comments

Seems to be simple but very helpfull.

I was just recently trying to figure out how to allow the addition of a server-side control in content generated in a CMS. Discussions were that this wasn't possible, which made sense. After careful consideration of the security issues, I think I'll be able to use this. Thanks.

simple and helpful

I could be wrong (its been a while so I am not positive j/k) but I believe that is will be important that you parse the string and add the resulting control to the page's control tree BEFORE the page lifecycle's LoadViewState event on postback.

pretty cool

Smart work like this can saves lots of time

Hi, I want to use a linkbutton. I put the code inside the html. - asp:LinkButton id=\"lbReply\" runat=\"server\" OnClick=\"lbReply_Click\">Reply/asp:LinkButton>". This creates a linkbutton control. But the postback doesnt call the event lbReply_Click(). Any help on this regard would be greatly appreciated.

hi sunil try this protected void GenerateControl() { LinkButton lb = new LinkButton(); lb.ID = "lb"; lb.Click += new EventHandler(lb_Click); lb.Text = "click me"; pnlPlace.Controls.Add(lb); } void lb_Click(object sender, EventArgs e) { Response.Write("hello"); }

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. abiruban (1)