Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 520
  • Last Modified:

How to mantain user control viewstate on page_load after postback?

Hi,

The piece of code below is to programatically add a user control. The problem that i have is that, on the page_load event, after a postback, the data in the textboxes are GONE.

I do not have this problem if i put the code in the button_click event. The data in the textboxes can be maintained after a postback.

Any help is greatly appreciated.

PS: Unless i entered the data manually on the textboxes with the code in page_load event, then the data is able to be maintained after a postback. Do not want this though.


Dim TextModule As TextModule = LoadControl("~/UserControl/Text.ascx")
        TextModule.ID = "TextModule" & Session("ctrl_id_increment")
 
        'Add in to page placeholder
        PlaceHolder1.Controls.Add(TextModule)
        PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
 
        'Find all the hidden web controls
        Dim txtSequence As TextBox = TextModule.FindControl("txtSequence")
        Dim txtControlID As TextBox = TextModule.FindControl("txtControlID")
        Dim txtType As TextBox = TextModule.FindControl("txtType")
 
        'Get and assign identifier to each user control
        txtSequence.Text = Session("ctrl_id_increment")
        txtControlID.Text = Session("ctrl_id_increment")
        txtType.Text = "TextModule"
 
        'Finally add the controls to the string list.
        ctrls.Add(String.Format("{0}|{1}", "TextModule", Session("ctrl_id_increment")))

Open in new window

0
tangteng78
Asked:
tangteng78
2 Solutions
 
Anurag ThakurTechnical ManagerCommented:
read this - a very good article for the same issue
http://www.4guysfromrolla.com/articles/092904-1.aspx
0
 
strickddCommented:
When working with dynamic controls you need to remember several things:

1) The control MUST have the exact same ID each time it is created. This allows .Net to associate the viewstate data with the correct control

2) Setting the value of a control should ONLY occur when !Page.IsPostBack

3) Controls should be created at Page_Load or earlier ideally.
protected void Page_Load(object sender, EventArgs e)
{
    TextBox myTest = new TextBox();
    myText.ID = "MyText";
 
    Page.Controls.Add(myText);
 
    if(!Page.IsPostBack)
       myText.Text = "Preset Text";
}

Open in new window

0
 
tangteng78Author Commented:
bulls eye
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now