Dynamically creating asp.net control from a string

Dynamically adding controls to a page is interesting aspect of development.Sometime we need to have control and it should be generated from a string.

 Dynamically adding html control to a Page from a string

 

protected PlaceHolder plhEdit;
public
void btnCheck_Click(object sender, EventArgs e)
{
  LiteralControl
 editbtn = new LiteralControl(string.Format("<input                             type=\"button\"  value=\"Edit\" onclick=\"{0}\"      />", scrpt));
plhEdit.Controls.Add(editbtn);
}


For example on a button click add a html button to a page from a string created at run time. Literal control comes handy in this case because it could hold desired html control as text. So in above code create a literal control with text value as html control and add it into a placeholder.

Dynamically adding Asp.net Control to a page from a string

using System.Web.UI.TemplateControl.ParserControl;
protected
PlaceHolder plhEdit;

public void btnCheck_Click(object sender, EventArgs e)
{

Control c = ParseControl("<asp:button text='Edit' runat='server' />");
plhEdit.Controls.Add(editbtn);

}

For example on a button click add a html button to a page from a string created at run time. Parse control comes handy in this case because it could parse text to a control. So in above code using parser control  to convert/parse the text to a asp.net control and add it into a placeholder.