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: -
<html xmlns="http://www.w3.org/1999/xhtml">
-
<body>
-
<form id="MainForm" runat="server">
-
<asp:ListBox ID="ctrlDynList" runat="server" />
-
<br />
-
<asp:Button ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" runat="server" />
-
</form>
-
</body>
-
</html>
-
Code behind:
... -
public partial class MultiSelect : Page {
-
protected void Page_Load(object sender, EventArgs e) {
-
if(!IsPostBack) {
-
ctrlDynList.Items.Add(new ListItem("One", "1"));
-
ctrlDynList.Items.Add(new ListItem("Two", "2"));
-
}
-
}
-
...
-
}
Here is the code with viewstate not working:
Page: -
<%@ Register Src="~/Test/SimplePanel.ascx" TagPrefix="uc" TagName="SimplePanel" %>
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<body>
-
<form id="MainForm" runat="server">
-
<uc:SimplePanel ID="ctrlDynList" runat="server" />
-
<br />
-
<asp:Button ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" runat="server" />
-
</form>
-
</body>
-
</html>
Code behind:
... -
public partial class MultiSelect : Page {
-
protected void Page_Load(object sender, EventArgs e) {
-
if(!IsPostBack) {
-
ctrlDynList.Items.Add(new ListItem("One", "1"));
-
ctrlDynList.Items.Add(new ListItem("Two", "2"));
-
}
-
else {
-
// The ctrlDynList.Items is empty in this case.
-
// It is not loaded from the viewstate like it does
-
// in the case when the ListBox is placed on the page (not inside a user control)
-
}
-
}
-
...
-
}
User control: -
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SimplePanel.ascx.cs" Inherits="MgScopes.MgScopesWeb.Test.SimplePanel" %>
-
<asp:ListBox ID="ctrlListBox" runat="server" />
-
Code behind:
... -
public partial class SimplePanel : UserControlBase {
-
protected void Page_Load(object sender, EventArgs e) {
-
}
-
-
public ListItemCollection Items {
-
get { return ctrlListBox.Items; }
-
}
-
}
-
...
-
}
6 8358
place your page_load event on the user control page not on main page and check your problem will be solved.
maliksleo
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.
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: -
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ctrl.ascx.vb" Inherits="ScratchPad.ctrl" %>
-
<div>
-
<asp:ListBox ID="theList" runat="server" AutoPostBack="true"></asp:ListBox>
-
<asp:Label ID="selectedItem" runat="server"></asp:Label>
-
</div>
The code behind for the user control: -
Public Partial Class ctrl
-
Inherits System.Web.UI.UserControl
-
Public ReadOnly Property Items() As ListItemCollection
-
Get
-
Return theList.Items
-
End Get
-
End Property
-
-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
-
End Sub
-
-
Private Sub theList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles theList.SelectedIndexChanged
-
Dim selectedItemText As String = theList.SelectedItem.Text
-
selectedItem.Text = selectedItemText
-
End Sub
-
End Class
The aspx page: -
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm3.aspx.vb" Inherits="ScratchPad.WebForm3" %>
-
<%@ Register TagPrefix="uc" TagName="ListUserControl" Src="~/ctrl.ascx" %>
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head runat="server">
-
<title></title>
-
</head>
-
<body>
-
<form id="form1" runat="server">
-
<uc:ListUserControl runat="server" ID="theListControl" />
-
</form>
-
</body>
-
</html>
-
The code behind for the aspx page: -
Partial Public Class WebForm3
-
Inherits System.Web.UI.Page
-
Private _gridViewDataSource As DataView
-
Private _detailsSource As DataSet
-
-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
If IsPostBack = False Then
-
theListControl.Items.Add(New ListItem("First Item", "1"))
-
theListControl.Items.Add(New ListItem("Second Item", "2"))
-
End If
-
End Sub
-
End Class
Like I said, this works perfectly fine.
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.
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.
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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";
|
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...
|
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...
|
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...
| |
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...
|
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.
|
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
|
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");
...
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |