Link to home
Start Free TrialLog in
Avatar of TomWisno
TomWisno

asked on

How to dynamicaly load a ASP.NET web control and add it to a ASPX page

I am having a problem loading controls dynamically at runtime.

To re-create my problem:
Create a ASPX page and add a placeholder and a button the the page.

In the code behind, in page_load, do the following:
TextBox txt = new TextBox();
if(!IsPostBack)
{
 txt.Text = "Hello";
txt.BackColor = Color.Yellow;
}

plchldr.Controls.Add(txt);

Run the page,

You will notice the textbox gets rendered correctly (text and color). Then press the button to post back...
The control never loads it's view state to set the backcolor. When the page get rendered out on postback, the backcolor is cleared.

I tested this by creating my own user control that inherits the TextBox. I overrided the SaveViewState and LoadViewState fucntions to add trace ouput so i can see when they are called. This is what i found...

When the page first loads, Save view state is called twice (not sure why?).
When the page posts back for the first time, the LoadViewState method of the control is not called.
When the page posts back again (postback 2 to infinity) the LoadViewState function is called as soon as the control is added to the placeholder controls collection.

Why is LoadviewState not called on the first postback?

Any comments would be appreciated...

Thanks!

Tom Wisnowski
Avatar of aponcealbuerne
aponcealbuerne

Avatar of TomWisno

ASKER

Thanks for the link... However it still doesn't answer the question.

The article does make mention to the fact that dynamic controls "between" static controls can cause a problem with the viewstate, but this doesn't seem to be my case.

The article says what i am doing should work fine. but unfortunately it doesn't.

Have you tried to repro this? if you need i can send the project to you so you can see for yourself...

Thanks,

Tom Wisnowski, MCAD
TomWisno,
It is important to assign an id for each control your created in .NET environment(web form).
[eliminate if(!IsPostBack)] - your control need to re-create for each postBack, it's not same with keep viewstate information.
Moreover, it advisable to assign an id for each control your create.
eg:

private void Page_Load
{
TextBox txt = new TextBox();
txt.ID="controlID"
txt.Text = "Hello";
txt.BackColor = Color.Yellow;

plchldr.Controls.Add(txt);
}

Regards
x_com


Use "LoadControl" command. It's quite simple and straightforward.
Sub Page_Load
            Dim myform As Control
            myform = FindControl("Form1")

            Dim c1 As Control = LoadControl("usercontrol1.ascx")
            CType(c1, usercontrol1).strCaption = "DD 2807"
            myform.Controls.Add(c1)
            c1.ID = "dd2807"

            myform.Controls.Add(New HtmlGenericControl("hr"))


Also try
http://www.dotnet101.com/articles/art020_DynamicUserControls.asp
Thank you all for your comments,

I did not correctly convey what i was doing in page load... this is my code...

private void Page_Load
{
  TextBox txt = new TextBox();
  txt.ID = "MyTextBoxID";
 
   if(!IsPostBack)
   {
    txt.Text = "Hello";
    txt.BackColor = Color.Yellow;
   }

   plchldr.Controls.Add(txt);
}

As you can see, I create the control on every postback and I assign it the same ID every time. I also add it to the same place in the control tree, using a placeholder. The first time the page loads, i set the text and backcolor (which the textbox control should store in the viewstate).

The problem is the control does not load the viewstate on the first postback. I can see this because, like i said earlier, I created a new custom control that inherits from  TextBox. I then overrided the LoadViewState and SaveViewState functions of the control to add trace statements to see when they fire. I observed that the loadviewstate function is called after the first postback, not the first. I belive this to be an error.

If anyone can get the above code to work, please let me know how...

Thanks,

Tom Wisnowski, MCAD

P.S.
Rohitmr, thank you for your comment, but the LoadControl function loads user controls, which is not what i'm trying to do. I am trying to load the System.Web.UI.WebControls.TextBox control. And, actually, its not a problem loading the control and adding it to the page, the problem is getting the control to save it's viewstate.



TomWisno ,
LoadViewState happens before the page_load event, that's why you face this problems. Dont rely on them. More details, please refer :
http://www.15seconds.com/issue/020102.htm.

You always can use ViewState[] inside Page_Load event to create the control dynamically. This method is recommended in the way of create the control dynamically.

eg:
private void Page_Load
{
 TextBox txt = new TextBox();
 txt.ID = "MyTextBoxID";
 
        If (ViewState["TxtBoxText"]==Null)
            ViewState["TxtBoxText"] = "Hello"
        End If

        If (ViewState["TxtBoxColor"]==Null)
            ViewState["TxtBoxColor"] = Color.Yellow
        End If

        txt.Text = ViewState["TxtBoxText"]
        txt.BackColor = ViewState["TxtBoxColor"]

  plchldr.Controls.Add(txt);
}

Regards
x_com
According to Dino Esposito in the following article http://devcenter.infragistics.com/Articles/ArticleTemplate.Aspx?ArticleID=2149
your statment is not entirely true. Yes, LoadViewState is called before page load (for the page which calls the control's loadviewstate), but for dynamic controls it is different. The dynamic control's LoadViewState function is called when the control is added to the page's control tree.

Take a look at the article add let me know what you think....

Thanks,

Tom
TomWisno,
Sorry for delay. After few day read from others article too, i noticed that http://devcenter.infragistics.com/Articles/ArticleTemplate.Aspx?ArticleID=2149 had point out the correct directions. But, LoadViewState and SaveViewState already gave me a lot of trouble. I think .NET havent complete consider about this problems??? I would like to Create control dynamically inside Page_Load event based on ViewState created.Maybe i could be wrong. But, this method always work well for me.

Regards
x_com  
Have viewstate("ISAdd") to check if the controls have been added...

Link for

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vbcode/html/vbtskCodeExampleAddingControlsAtRuntime.asp


  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        If Not IsPostBack Then
            Dim t2 As TextBox
            t2 = addtextbox()
        End If

        If IsPostBack Then
            If ViewState("AddedControl") = True Then
                Dim t2 As TextBox

                t2 = addtextbox()
            End If
        End If

    End Sub

    Private Function addtextbox() As TextBox
        Dim ctl As New TextBox()
        ctl.Text = "Hello"
        PlaceHolder1.Controls.Add(ctl)
        ViewState("AddedControl") = True
        ctl.MaxLength = 1
        ctl.BackColor = Color.Yellow
        addtextbox = ctl
    End Function
Thanks for your comments x_com,

I think this might be a bug with how dynamic controls handle thier viewstate. The technique in http://devcenter.infragistics.com/Articles/ArticleTemplate.Aspx?ArticleID=2149  seems to work for dino becuase he creates the dynamic text box "AFTER" the initial page load, in the post back event handler for the button on his form. Then he sets a flag in the viewstate he checks on every postback, and if set he re-creates his dynamic contorl. This doesn't work if he creates his dynamic control on the first page load, even though he re-creates the control on every postback. I believe this to be a bug. Let me know what you think...

nishikanth,

Thank you for your code sample. However, your sample does not demonstrate the dynamic textbox using it's viewstate correctly because your re-initialize your textbox's properties (ie. maxLength, backColor) every time you create the control. This is what the viewstate is for... The first time you create the control and set those proerties, the values of those properties should be saved to the viewstate before the page renders. When the page postsback, the control should load it's viewstate and restore those properties (given you re-created the control, give it the same id, and add it to the page's control tree). This doesn't seem to work correctly, and i think it might be a bug. I plan on opening a case with microsoft to determine if it is a bug or not. But thanks for your reply never the less! :)

If anyone can confirm my suspicions, let me know.

Thanks everyone,

Tom Wisnowski, MCAD
TomWisno,
After i review few of the articles, i can confirm that LoadViewState or SaveViewState is related wirh PostBack features. That's why it can't be initial for FIRST load of the page. This is not a bugs, but it was the characteristic of ViewState itself because it depend  PostBack event.
More details, you can check out the definations for
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIUserControlClassLoadViewStateTopic.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIUserControlClassLoadViewStateTopic.asp

Regards
x_com
Hi TomWisno,


 I think i gave you the wrong code.
Check out this link, which gives u how to work about the dynamic controls.

http://devcenter.infragistics.com/Articles/ArticleTemplate.Aspx?ArticleID=2149
x_com,

I know load view state and save view state control the loading and saving of control state information via the view state on postbacks. I know this doesn't happen on page load because there is nothing in the view state at page load. What i am experiencing is that dynamic controls on first POSTBACK don't correctly initialize thier view state. On subsequent postbacks, everyting works as expected.

nishikanth,

Thanks for the link. I have already read this article (i actually posted the link a few comments ago). The article doesn't do exactly what i'm doing. Dino loads a dynamic control and adds it to the tree on POSTBACK, and everything works. I'm loading the control and adding it to the tree on the first page load. In Dino's example, his dynamic control never has to load the viewstate on the the first postback of the page. His control get created in response to a button click, I create the control on page load.

If there is a way for me to send a ZIP file, let me know. I will send my example code that clearly outlines what is happening.

Thanks,

Tom Wisnowski, MCAD
ASKER CERTIFIED SOLUTION
Avatar of nishikanth
nishikanth

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ding Ding! We have a winner. I assumed that I could set the properties after they were added to the control tree, but i was mistaken. thanks you for clearing up the issue.

nice spot:-)