Abe Miessler
Abe Miessler

Reputation: 85126

How to dynamically render a control?

How do I go about rendering an asp.net control on a web page from a string in code behind?

For example, say I have the aspx page below:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        //want to render a text box here
    </div>
    </form>
</body>
</html>

What could I do in my Page_Load event to render a TextBox into the div?

protected void Page_Load(object sender, EventArgs e)
{
    //what do i do here to render a TextBox in the div from the aspx page?
}

Upvotes: 2

Views: 3588

Answers (3)

Jonathan Park
Jonathan Park

Reputation: 775

Caution there may be compilation problems here. But basically add a placeholder control to the code in front as such.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:placeholder id="placeHolder" runat="server"/>
    </div>
    </form>
</body>
</html>

Then create a TextBox in the code behind programmatically. You will need to include System.Web.UI in order to get the textbox. Then Add the control to the controls collection on the placeHolder. Set whatever properties you like on the text box programmatically

protected void Page_Load(object sender, EventArgs e)
{
    TextBox tb = new TextBox();
    placeHolder.Controls.Add(tb); //tb is referring to the name that you want to name your element. in this example given was TextBox. so the name of text box is tb. 

}

Upvotes: 2

Sanosay
Sanosay

Reputation: 578

Easy.

Add two attributes to your div element : <div runat="server" id="myDiv"></div>

Then

   TextBox tb = new TextBox();
   this.myDiv.Controls.Add(tb);

If you want to render a Custom UserControl you can use the above code

  MyUserControl control  = (MyUserControl)Page.LoadControl("~/My_VirtualPathToControl");
  this.myDiv.Controls.Add(control);

(You must register your control in the aspx file)

One more think. Be cautious when you execute code on Page_Load event.

Upvotes: 2

Tehrab
Tehrab

Reputation: 57

You will also need to rebuild the controls in the Page_Init method in order to read the controls' state/values on PostBack.

protected void Page_Init(object sender, System.EventArgs e)
{
    TextBox tb = new TextBox();
    placeHolder.Controls.Add();
}

Upvotes: 0

Related Questions