Solved

restoring the view state of user control.

Posted on 2004-09-03
26
304 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 14
  • 12
26 Comments
 

Author Comment

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

Expert Comment

by:daffodils
ID: 11973433
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
ID: 11973849
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
Industry Leaders: 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!

 
LVL 8

Expert Comment

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

0
 

Author Comment

by:rxraza
ID: 11974189
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
ID: 11974252
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
ID: 11974895
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
ID: 11974982
>>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
ID: 11975027
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
ID: 11975060
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
ID: 11975121
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
ID: 11975143
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
ID: 11975287
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
 

Author Comment

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

Expert Comment

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

Author Comment

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

0
 

Author Comment

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

Expert Comment

by:daffodils
ID: 11975686
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
ID: 11976325
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
ID: 11976620

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
ID: 11977066
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
ID: 11977105
You are right there...
0
 

Author Comment

by:rxraza
ID: 11977234
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
ID: 11977540
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
ID: 11997350
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
ID: 11998357
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

631 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