posts - 225, comments - 306, trackbacks - 56

My Links

News




I am born in Bangladesh and currently live in Melbourne, Australia. I am a co-founder and core developer of Pageflakes www.pageflakes.com and CEO at Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh.

I also created SmartCodeGenerator

Some of my articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

ASP.NET tips: Golden rules for Dynamic Controls.

1. Make sure your dynamic controls are Loaded on every postback.

Lets play with a very simple example,

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>


C# Code Behind

public partial class _Default : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
        this.PlaceHolder1.Controls.Add(t);        
    }

}

The above code works fine, but a common mistake is to try to conditionally load dynamic controls, if we tweak the code a little bit you will notice we loose our TextBox after any postback. The following code will not load the TextBox after our first postback.

public partial class _Default : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {      
       if (!IsPostBack)
        {
            TextBox t = new TextBox();
            t.ID = "textBox";
            this.PlaceHolder1.Controls.Add(t);
        }
    }

}

Its recommended to load the dynamic controls during the Page_Init instead, because we may want to hook up our events with proper handler at an early stage.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
        t.TextChanged+=new EventHandler(t_TextChanged);
        this.PlaceHolder1.Controls.Add(t);
    }

}


2. Do not assigning properties of a dynamic control (viewstate enabled), during Page_Init, it will not be reflected.

Here is scenario of another common mistake, "123" assigned to the Text property during Page_Init,

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
       t.Text = "123";
        this.PlaceHolder1.Controls.Add(t);
    }

}

controllifecycle

the above code will not work because, Initialization happens before LoadViewState during the control lifecycle. The value assigned to the properties during Initialization will simply get overwritten by the ViewState values.

 

3. If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control

The following piece of code will not work, as I am assigning a new ID to the dynamic control after each postback. The LoadViewState retrieves previously saved viewstate data using the control ID, as the control ID has changed, it doesn't know anymore what to load, as a result it cannot load previously saved viewstate data any more.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = Guid.NewGuid().ToString();
        this.form1.Controls.Add(t);       
    }
}

Thank you for being with me so far.

Print | posted on Thursday, June 26, 2008 2:36 AM |

Feedback

Gravatar

# re: ASP.NET tips: Golden rules for Dynamic Controls.

I have problem with dyanmic control:

C# Code:

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

TextBox t = new TextBox();
t.ID = DateTime.Now.Ticks.ToString();
t.Text = "22";
t.EnableViewState = false;
this.form1.Controls.Add(t);


}
}



ASPX PAGE:

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>



I am confused here bcz when i set some value in text box , text box is not losting that value. So, please put a light on this issue how it happen?


8/7/2008 12:48 AM | Anoop
Gravatar

# re: ASP.NET tips: Golden rules for Dynamic Controls.

If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control .

Here your ID is

t.ID = DateTime.Now.Ticks.ToString();

the value of the ID will change on every postback.

Try assigning the same id on every postback.

Example: t.ID = "TextBox1";
8/7/2008 1:01 AM | Shahed Khan
Gravatar

# i need a help for while craeting events for dynamic buttons

hello,
i'm using a code in asp.net with c# which dynamically generates 6 textboxes, 2 dropdownlist box and 2 buttons.
can anyone help me with the code, how can i perform addition of 2nd textbox with 2nd dropdownlist box when each respective dynamically created button is clicked.??

i.e, when first times the controls r created then 2nd textbox + 2nd dropdownlistbox value on 3rd textbox when dynamic button is clicked

when again the contorls r created for the second time again 2nd textbox + 2nd dropdownlistbox value on 3rd textbox when dynamic button is clicked
and so on..
1/23/2009 5:29 PM | Arvind
Gravatar

# Alternate approach to generate dynamic buttons and handle events

See here for generating dynamic buttons and handle events
http://urenjoy.blogspot.com/2009/02/add-dynamic-buttons-and-handle-click.html
2/18/2009 4:16 PM | urenjoy
Gravatar

# re: ASP.NET tips: Golden rules for Dynamic Controls.

You're right. I've been using it for awhile, and I thought it was pretty commonly accepted. It is definitely out there, but less so than I thought. I'm going to change it in the article, and at some point in the future I'll do an article on this term alone.
Instant Activation Hosting
5/18/2009 9:39 PM | Instant Activation Hosting

Post Comment

Title  
Name  
Email
Url
Comment   

Powered by: