473,756 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ListBox inside UserControl ViewState lost

3 New Member
Hi, everybody. I have this problem. When I put a <asp:ListBox on a web page and populate the data in the page Page_Load event the ViewState for the control is saved and loaded (after postback) correctly. In other words the Items property of the ListBox is populated from the ViewState after the postback. However if I put this ListBox inside a UserControl, expose the Items list, and populate it with the data in the same manner (in the page Page_Load event), the data is lost after the postback. What is wrong?

Here is the code with viewstate working:

Page:
Expand|Select|Wrap|Line Numbers
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <body>
  3. <form id="MainForm" runat="server">
  4.    <asp:ListBox ID="ctrlDynList" runat="server" />
  5.    <br />
  6.    <asp:Button ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" runat="server" />
  7. </form>
  8. </body>
  9. </html>
  10.  
Code behind:
...
Expand|Select|Wrap|Line Numbers
  1.    public partial class MultiSelect : Page {
  2.       protected void Page_Load(object sender, EventArgs e) {
  3.          if(!IsPostBack) {
  4.             ctrlDynList.Items.Add(new ListItem("One", "1"));
  5.             ctrlDynList.Items.Add(new ListItem("Two", "2"));
  6.          }
  7.       }
  8. ...
  9. }
Here is the code with viewstate not working:

Page:
Expand|Select|Wrap|Line Numbers
  1. <%@ Register Src="~/Test/SimplePanel.ascx" TagPrefix="uc" TagName="SimplePanel" %>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <body>
  4. <form id="MainForm" runat="server">
  5.    <uc:SimplePanel ID="ctrlDynList" runat="server" />
  6.    <br />
  7.    <asp:Button ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" runat="server" />
  8. </form>
  9. </body>
  10. </html>
Code behind:
...
Expand|Select|Wrap|Line Numbers
  1.    public partial class MultiSelect : Page {
  2.       protected void Page_Load(object sender, EventArgs e) {
  3.          if(!IsPostBack) {
  4.             ctrlDynList.Items.Add(new ListItem("One", "1"));
  5.             ctrlDynList.Items.Add(new ListItem("Two", "2"));
  6.          }
  7.          else {
  8. // The ctrlDynList.Items is empty in this case.
  9. // It is not loaded from the viewstate like it does
  10. // in the case when the ListBox is placed on the page (not inside a user control)
  11.          }
  12.       }
  13. ...
  14. }
User control:
Expand|Select|Wrap|Line Numbers
  1. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SimplePanel.ascx.cs" Inherits="MgScopes.MgScopesWeb.Test.SimplePanel" %>
  2. <asp:ListBox ID="ctrlListBox" runat="server" />
  3.  
Code behind:
...
Expand|Select|Wrap|Line Numbers
  1.    public partial class SimplePanel : UserControlBase {
  2.       protected void Page_Load(object sender, EventArgs e) {
  3.       }
  4.  
  5.       public ListItemCollection Items {
  6.          get { return ctrlListBox.Items; }
  7.       }
  8.    }
  9. ...
  10. }
Jul 23 '09 #1
6 8358
maliksleo
115 New Member
place your page_load event on the user control page not on main page and check your problem will be solved.

maliksleo
Jul 24 '09 #2
kucheravy
3 New Member
I tried all those kind of things. I finally found the answer I could never think on. In completely separate part of my code, not concerned to this sample, I called Controls.AddAt( Number, Control). This call blows ViewState for all controls in the collection and it seems like not only in this collection (I didn't investigate futher). It looks like the Framework keeps control's positions deep inside and if the positions change it cannot bind the ViewState to the controls. So, basically, if you care about the ViewState never call AddAt. Call Controls.Add instead. It works fine.
Jul 24 '09 #3
Frinavale
9,735 Recognized Expert Moderator Expert
It doesn't really matter how you fill the control you should not be experiencing this.
Maliksleo's suggestion is good because it makes more sense to make the user control responsible for maintaining the list.

I tested what you posted and could not reproduce your problem.

This is what I have.

The user control:
Expand|Select|Wrap|Line Numbers
  1. <%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ctrl.ascx.vb" Inherits="ScratchPad.ctrl" %>
  2. <div>
  3.     <asp:ListBox ID="theList" runat="server" AutoPostBack="true"></asp:ListBox>
  4.     <asp:Label ID="selectedItem" runat="server"></asp:Label>
  5. </div>
The code behind for the user control:
Expand|Select|Wrap|Line Numbers
  1. Public Partial Class ctrl
  2.     Inherits System.Web.UI.UserControl
  3.     Public ReadOnly Property Items() As ListItemCollection
  4.         Get
  5.             Return theList.Items
  6.         End Get
  7.     End Property
  8.  
  9.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  10.  
  11.     End Sub
  12.  
  13.     Private Sub theList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles theList.SelectedIndexChanged
  14.         Dim selectedItemText As String = theList.SelectedItem.Text
  15.         selectedItem.Text = selectedItemText
  16.     End Sub
  17. End Class
The aspx page:
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm3.aspx.vb" Inherits="ScratchPad.WebForm3" %>
  2. <%@ Register TagPrefix="uc" TagName="ListUserControl" Src="~/ctrl.ascx" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head runat="server">
  6.   <title></title>
  7. </head>
  8. <body>
  9.     <form id="form1" runat="server">
  10.     <uc:ListUserControl runat="server" ID="theListControl" />
  11.     </form>
  12. </body>
  13. </html>
  14.  
The code behind for the aspx page:
Expand|Select|Wrap|Line Numbers
  1. Partial Public Class WebForm3
  2.     Inherits System.Web.UI.Page
  3.     Private _gridViewDataSource As DataView
  4.     Private _detailsSource As DataSet
  5.  
  6.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  7.         If IsPostBack = False Then
  8.             theListControl.Items.Add(New ListItem("First Item", "1"))
  9.             theListControl.Items.Add(New ListItem("Second Item", "2"))
  10.         End If
  11.      End Sub
  12. End Class
Like I said, this works perfectly fine.
Jul 24 '09 #4
Frinavale
9,735 Recognized Expert Moderator Expert
@kucheravy
Oh! I see what the problem is.

If you're calling the ControlCollecti on.AddAt() method then you're probably dynamically adding controls to your page. You did not mention this fact in your explanation of the problem...in fact your example code doesn't show you dynamically adding the control at all.

The reason the ViewState isn't being remembered in your case is because of how the ASP Page Life Cycle works...

This is what's happening:

The web browser makes a request for the page.

The Page Init Event occurs and all of the Objects required to do page processing are created.

Right After the Page Init Event the ViewState of the controls are loaded.

If your dynamically creating controls in the Page Load (or after that in the life cycle) then the ViewState for the control is not loaded because the Object doesn't exist!

So, if you want the ViewState to load for dynamic controls, then you'll have to instantiate them (use the "new" statement) in the Page Init event. You also have to add them to their appropriate containers at this point too or you're going to experience a validation exception.
Jul 24 '09 #5
kucheravy
3 New Member
I agree with your explanation and I new that. The problem is that as soon as you use Constrols.AddAt no controls that were already statically created and loaded into the Controls could Save/Load their state. It is not a problem of that one control that I add dynamically by AddAt. The whole collection of the controls loses the viewstate. BUT if you use Add everything is fine for the whole colleciton and that dynamically added control. I just wanted to state this problem for other people who might have the similar problem. I wasted a day figuring this out.
Jul 24 '09 #6
Frinavale
9,735 Recognized Expert Moderator Expert
Hmm I've never used the AddAt method before. I've always used the Add method.

I guess it makes sense that it would mess up the static controls when you use the AddAt method though...becaus e something else (a static control) could be at that index.

Thanks for added the info :)

-Frinny
Jul 25 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
7873
by: R.Wieser | last post by:
Hello All, I'm trying to get a "Virtual Listbox" to work. I've currently got a form, and used CreateWindowExA to create a ListBox with the LBS_OWNERDRAWFIXED and LBS_NODATA flags on it. I've allso subclassed the window and do see all kinds of WS_??? messages coming by. But now I'm stuck :-\ I've got *no* idea what to do next, and all my searching on the web leads me
2
1355
by: Cederstrom | last post by:
Hello Group, I have created an ASP.NET page. The page consist of the following items: - Button A - Button B - UserControl When I press Button A, I execute the following code: ViewState = "edit"; Session = "edit";
1
8421
by: Edward | last post by:
I am having a terrible time getting anything useful out of a listbox on my web form. I am populating it with the results from Postcode lookup software, and it is showing the results fine. What I want to do is to allow the user to click on the row that corresponds to the correct address, and have the code behind populate the form's Address1, Address2 etc. controls with the relevant data items. I put the code for this into the...
4
3119
by: Harry | last post by:
Hello, I have a page with a RadioButtonList and a PlaceHolder control. The RadioButtonList's AutoPostBack attribute is set to TRUE and its SelectedIndexChanged event loads one of three UserControls into the PlaceHolder's child control collection depending upon which of the three radio buttons is selected. Each of the three UserControls have postback events themselves triggered by button clicks. The problem I'm having is keeping track of...
6
5225
by: Janaka | last post by:
Help! I have two ListBox controls on my web form. The first one gets populated on entry with values from the DB. I then use JavaScript to copy options from this ListBox to my second one. (I have also tried changing the second ListBox to an HtmlSelect control) using bog standard JavaScript code like so where "used" is the name of my <select> control: used.options = new Option(name, typeId); This all works fine and I can move across...
0
1534
by: Matt Howeson | last post by:
I have a problem with a usercontrol that is dynamically loaded, from a web control and is not restoring it's viewstate properly. Here's the scenario. Within our content management system, I have a webcontrol which allows a admin user to select a usercontrol to include within a page when in "edit mode". When a user is editing the page they see a dropdown list of available controls and select one and save the page, kind of irrelevant to...
1
3456
by: Tim | last post by:
Greetings! I have a UserControl. On this UserControl is a Panel and a RadioButtonList. The Panel's Visible property is set to false by default. When the user selects a particular RadioButtonList value, a postback is performed and the Panel's Visible property is set to true. Selecting a different RadioButtonList value sets the Visible property to false again. So far, so good. It does, in fact, do this.
5
1869
by: Alex Maghen | last post by:
Hi. If I create a WebControl (User Control, actually), I know how, easily, to access the design-time Properties that have been set as Propertiy nodes in the tag used on the ASPX page. But I've never tried having CONTENT inside my Control's Tag, e.g.: <Ax:MyCtl id="Something" runat="server"> Some stuff inside the tag </Ax:MyCtl> How do I access the body from the code of my Control (i.e. above, "Some
1
3431
by: stimul8d | last post by:
okay; ASP. I have i listbox inside a user control which is dynamically created on page_init. I check for postback and only populate the datasource if it's false. regardless, i do this foreach (Product p in manager.Products) { ASP.MasterDetailDropDown productMasterDetail; productMasterDetail = (ASP.MasterDetailDropDown)LoadControl("~/controls/MasterDetailDropDown.ascx"); ...
0
9455
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9271
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10031
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9838
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.