Solved

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

Posted on 2003-11-26
17
5,439 Views
Last Modified: 2007-12-19
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
0
Comment
Question by:TomWisno
  • 6
  • 5
  • 3
  • +2
17 Comments
 
LVL 4

Expert Comment

by:aponcealbuerne
Comment Utility
0
 

Author Comment

by:TomWisno
Comment Utility
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
0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
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


0
 
LVL 1

Expert Comment

by:Rohitmr
Comment Utility
Use "LoadControl" command. It's quite simple and straightforward.
0
 
LVL 1

Expert Comment

by:Rohitmr
Comment Utility
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
0
 

Author Comment

by:TomWisno
Comment Utility
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.



0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
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
0
 

Author Comment

by:TomWisno
Comment Utility
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
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
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  
0
 
LVL 8

Expert Comment

by:nishikanth
Comment Utility
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
0
 

Author Comment

by:TomWisno
Comment Utility
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
0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
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
0
 
LVL 8

Expert Comment

by:nishikanth
Comment Utility
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
0
 

Author Comment

by:TomWisno
Comment Utility
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
0
 
LVL 8

Accepted Solution

by:
nishikanth earned 500 total points
Comment Utility
to retain your viewstate, add your control on before checking for your post back.


 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim txt As New TextBox()
        txt.ID = "MyTextBoxID"
        plchldr.Controls.Add(txt)             ''''' Add your control here instead of after the end if...

        If Not IsPostBack Then
            txt.Text = "Hello"
            txt.BackColor = Color.Yellow
        End If
end sub
0
 

Author Comment

by:TomWisno
Comment Utility
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.

0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
nice spot:-)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Preface This article introduces an authentication and authorization system for a website.  It is understood by the author and the project contributors that there is no such thing as a "one size fits all" system.  That being said, there is a certa…
There are two main kinds of selectors in CSS: One is base selector like h1, h2, body, table or any existing HTML tags.  For instance, the following rule sets all paragraphs (<p> elements) to red: (CODE) CSS also allows us to define our own custom …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now