Solved

restoring the view state of user control.

Posted on 2004-09-03
26
291 Views
Last Modified: 2012-05-05
Hi folks:

I am loading a user control containing a bunch of textboxes, dynamically using

System.Web.UI.Control c = Page.LoadControl("usr/customControl1.ascx");
this.placeHolder1.Controls.Add(c)

but the problem is on PostBack the State of Text Boxes inside the user control is not maintained. How do I resolve this and why I am having this problem in the first place. I think in ASP.NET the view state is maintained during postbacks.

Below is a reduced section of my userControl

<table border=0 cellpadding=0 cellspacing=0 width="100%">
    <tr>
       <td>
            <table cellpadding=0 cellspacing=0 border=0 width="75%">
      <tr>
         <td class="contentMicrosoft_1">&nbsp;Last</td>
         <td><asp:textbox id="txtLast" runat="server" Width="150" maxLength="50"    
                              CSSClass="contentMicrosoftXSmall"></asp:textbox></td>
         <td class="contentMicrosoft_1">&nbsp;First</td>
         <td><asp:textbox id="txtFirst" runat="server" Width="150" maxLength="50"
                            CSSClass="contentMicrosoftXSmall"></asp:textbox></td>
         <td class="contentMicrosoft_1" width="10%">&nbsp;Middle</td>
         <td colspan="4"><asp:textbox id="txtMiddle" runat="server" Width="150" maxLength="50"
                          CSSClass="contentMicrosoftXSmall"></asp:textbox>
                   </td>
                </tr>
            </table>
        </td>
     </tr>
</table>
       
0
Comment
Question by:rxraza
  • 14
  • 12
26 Comments
 

Author Comment

by:rxraza
Comment Utility
Also, I am loading the usercontrol in an event handler which is not PageLoad.
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
Well ASP.NET does automatically save ViewState for ASP.NET controls, but not for user controls.
You would need to write code to save and restore settings from the user controls's ViewState.

Lets say you have a property called Value.. then its implementation would have to take care of setting and restoring values to and from ViewState.

public int Value
{
  get
  {
      return Convert.ToInt32(ViewState["Value"]);
  }

  set
  {
      ViewState["Value"] = value;
  }
}
0
 

Author Comment

by:rxraza
Comment Utility
So for my textBoxes having names first, last, middle t

I will have to come up with three sets of get/set in the User Control or what.

public string txtFirst
{
  get
  {
      return ViewState["txtFirst"].ToString();
  }

  set
  {
      ViewState["txtFirst"] = value;
  }
}

OR DO I have to derive a new textbox class and define a new propery Text and have a get/set pair and then use that class in my User Control

class TextBox1 : System.Web.UI.WebControls.TextBox{
  string Text;

public string Text
{
  get
  {
      return ViewState["CTL_TEXT"].ToString();
  }

  set
  {
      ViewState["CTL_TEXT"] = value;
  }
}



}
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
Nope .. just use your own user control file (or class) and add the ViewState stuff to get/set.

0
 

Author Comment

by:rxraza
Comment Utility
I do not know if your are familiar with the this customcontrol
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

It has the ability to persist the state of the controls that are created dynamically. I checked that out with standard asp.net controls and it worked but I am having problem with the user control, It is not persisting its state.

I am gonna try your approach now.
0
 

Author Comment

by:rxraza
Comment Utility
Below is my UserControl Class, Would you let me know how do I put a get/set pair . Have never done that in a user control

public class Contact : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.TextBox txtFirst;
protected System.Web.UI.WebControls.TextBox txtLast;
protected System.Web.UI.WebControls.TextBox txtMiddle;

private void Page_Load(object sender, System.EventArgs e)
{
   // Put user code to initialize the page here
}

}
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
Sorry.. I was not at my desk for a while.


>>Would you let me know how do I put a get/set pair .
Well just decalre it as it is..

public class Contact : System.Web.UI.UserControl
{
  protected System.Web.UI.WebControls.TextBox txtFirst;
  protected System.Web.UI.WebControls.TextBox txtLast;
  protected System.Web.UI.WebControls.TextBox txtMiddle;

  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
  }

  public string txtFirst
  {
    get
    {
      return ViewState["txtFirst"].ToString();
    }
   
    set
    {
      ViewState["txtFirst"] = value;
    }
  }

  public string txtLast
  {
    get {........}
    set {........}
  }

  public string txtMiddle
  {
    get {........}
    set {........}
  }

}

0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
>>I do not know if your are familiar with the this customcontrol
>>http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

Hmm.. no, I haven't used it before.

>>It has the ability to persist the state of the controls that are created dynamically. I checked that out with standard asp.net controls and it worked but I am having problem with the user control, It is not persisting its state.

If this is a custom control.. why are you using it as a user control ??
Register it.. add it to your Toolbox and add it like any other ASP.NET control...
0
 

Author Comment

by:rxraza
Comment Utility
no I meant to say that the custom control DynamicControlsPlaceholder.dll has problems persisting a user control. I am not using it as a user control. Through that control I want to persist a user control.
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
oh okay.. not sure if that would work.. as in if the 'custom control DynamicControlsPlaceholder.dll ' would be able to amaintain the state of a user control.
The rule is.. you make the control, you maintain it.
0
 

Author Comment

by:rxraza
Comment Utility
I did that now, I am getting the following error
class 'PatientFormsNet.UserControls.Patient.PatientContact' already contains a definition for 'txtFirst'

0
 

Author Comment

by:rxraza
Comment Utility
I totally agree with your rule
YOU MAKE THE CONTROL, YOU MAINTAIN IT
but the thing is HOW?
0
 
LVL 8

Accepted Solution

by:
daffodils earned 125 total points
Comment Utility
hell.. I messed it up!

Well you define get/set pairs for a property .. not for a control!
I think I mentioned it before.. and then I went ahead and made a mess out of it... kill me!

So, lets start afresh.. in your user control, you have 3 TextBoxes. And you have declared them as:
public class Contact : System.Web.UI.UserControl
{
  protected System.Web.UI.WebControls.TextBox txtFirst;
  protected System.Web.UI.WebControls.TextBox txtLast;
  protected System.Web.UI.WebControls.TextBox txtMiddle;
-------
}

Now you need to maintain their values..
Here is where the get/set would come in.. nit for the TextBoxes, but for the PROPERTY to be maintained.. Text!
public class Contact : System.Web.UI.UserControl
{
  protected System.Web.UI.WebControls.TextBox txtFirst;
  protected System.Web.UI.WebControls.TextBox txtLast;
  protected System.Web.UI.WebControls.TextBox txtMiddle;

  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
  }

  public string Text
  {
    get
    {
      return ViewState["Text"].ToString();
    }
   
    set
    {
      ViewState["Text"] = value;
    }

  }
}

There.. that should work! And once it does, throw me out !
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!

 

Author Comment

by:rxraza
Comment Utility
so one get/set pair would work for all those textboxes?
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
The property is defined for the User control "Contact" and it should maintain it for it.
0
 

Author Comment

by:rxraza
Comment Utility
No matter how many controls (textBoxes,DropDownLists,Check boxes, radioButtons etc) a user controls have

0
 

Author Comment

by:rxraza
Comment Utility
That worked like a cham.. you are the man...
thanks daffodils....
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
My pleasure.. actually I not a man ;)).. but that's okay :))
I am sorry .. I actually messed it up in between.. it would have started working long before by now.

best of luck !
0
 

Author Comment

by:rxraza
Comment Utility
I am confused. I thought that it worked but as a matter of fact that was the FORMS collection which was hoding the values of the control. On the post back I am not seeing my controls (those three textboxes) in the user control.

I could see their text values in the forms collection. Even if I take the get/set pair off the user control, the forms collection will have their values stored in it.

WHY MY CONTROLS ARE NOT APPEARING ON THE POST BACK.
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility

Post the code .. the file .. where you are using the User control..

I created a small 'add-subtract buttons and display result textbox' user control.. it works for me. wierd, huh!


0
 

Author Comment

by:rxraza
Comment Utility
The problem is I am creating the control in a different event hander other than Page.Load. So I think I will have to take care of creating the control every time a post back happens.

Any ways here is the source code.

public class testPage : System.Web.UI.Page
      {
            
            protected System.Web.UI.WebControls.Button btnSubmit;
            protected System.Web.UI.WebControls.Button btnPostBack;
            protected System.Web.UI.WebControls.PlaceHolder PlaceHolder1;
            protected System.Web.UI.WebControls.Button btnUserControl;
            
                                private void btnUserControl_Click(object sender, System.EventArgs e)
            {
                  System.Web.UI.Control c = Page.LoadControl("UserControls/Patient/PatientContact.ascx");
                  
                  ((PatientContact)c).ID = "ctlPatientContact";
                  ((PatientContact)c).Attributes.Add("familyno","213");
                  ((PatientContact)c).Attributes.Add("personno","01");
                  ((PatientContact)c).Attributes.Add("rank","01");
                  ((PatientContact)c).Attributes.Add("PREV_RANK","01");
                  this.PlaceHolder1.Controls.Add(c);
            }

            private void btnPostBack_Click(object sender, System.EventArgs e)
            {
                  //control is not recreated here.
            }
      }
}
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
You are right there...
0
 

Author Comment

by:rxraza
Comment Utility
see even if you do not include the set/get pair still the forms collection will hold the values. I think that is where the custom control

http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

comes in. If that custom controls is used, you do not have create the control every time a post back happens.
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
Hmm.. I read this from the site..

I have created a custom control called DynamicControlsPlaceholder that derives from Placeholder and overrides Load- and SaveViewState.
In SaveViewState, the control hierarchy is recursively traversed and the control type and ID persisted to a string
In LoadViewState the persisted information is used to recreate the control tree to the state before.

If this is true.. you shouldn't ned to create-recreate controls in Page_Load or save-reload ViewState values in get/set properties !
But it isn't working that way.. is it? umm.. you said that it works with ASP.NET controls.

Leave the user control aside for a while... Try adding three TextBox and one button control to this custom panel and disable ViewState.. if they don't retain values, there is something wrong with the custom panel.
0
 

Author Comment

by:rxraza
Comment Utility
I am sorry I was out of town for the weekend. Can you post the code for SaveViewState and LoadViewState
0
 
LVL 8

Expert Comment

by:daffodils
Comment Utility
Hope you enjoyed the Holidays :))

Actually I read that from the link you had sent me...

http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

""""""""""I have created a custom control called DynamicControlsPlaceholder that derives from Placeholder and overrides Load- and SaveViewState.In SaveViewState, the control hierarchy is recursively traversed and the control type and ID persisted to a string. In LoadViewState the persisted information is used to recreate the control tree to the state before."""""""""""""

So those functions should be there as a part of the downloaded code.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

772 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

10 Experts available now in Live!

Get 1:1 Help Now