Solved

i cannot figure out why I cannot pass Session Values across to another User control.

Posted on 2009-07-03
11
325 Views
Last Modified: 2012-08-14
I am lost.. i cannot figure out why I cannot pass Session Values across to another User control.
Where I have user controls attached to a page with a User control and then the Two User controls attached to the first User control.

Page
                                                                                                          <---  OrderSummary.ascx
CheckoutShippingMethod.aspx <- CheckoutShippingMethod.ascx - |
                                                                                                         <-- WC_CompiliantControl.ascx
I have this in webconfig

 <sessionState mode="InProc" cookieless="false" timeout="20" />
 

I have this in a user control - CheckoutShippingMethod.ascx
 

<%@ Control Language="C#" AutoEventWireup="true" Inherits="NopSolutions.NopCommerce.Web.Modules.CheckoutShippingMethodControl" Codebehind="CheckoutShippingMethod.ascx.cs" %>

<%@ Register TagPrefix="nopCommerce" TagName="OrderSummary" Src="~/Modules/OrderSummary.ascx" %>

<%@ Register TagPrefix="nopCommerce" Namespace="NopSolutions.NopCommerce.Common.UI" Assembly="Nop.Common" %>

<%@ Register TagPrefix="nopCommerce" TagName="WC_CompiliantControl" Src="~/Modules/WC_CompiliantControl.ascx" %>  
 

I have this in the user control - OrderSummary.ascx
 

foreach (RepeaterItem item in rptShoppingCart.Items)

                {

                    TextBox txtQuantity = item.FindControl("txtQuantity") as TextBox;

                    this.Session["uxQuantityText"] = txtQuantity.ToString();
 

I have the read session in this user control --> WC_CompiliantControl.ascx
 

Label5.text =   this.Session["uxQuantityText"] .ToString();
 

this does not work??
 

what I can do is pass Sessions within a User contorl

Open in new window

0
Comment
Question by:westdh
  • 5
  • 5
11 Comments
 
LVL 9

Expert Comment

by:Rahul Goel
ID: 24771422
you need to use the public properties within the user control class.
0
 
LVL 39

Expert Comment

by:abel
ID: 24771428
You are seemingly setting a single Session value multiple times inside a loop, where you are searching for different textboxes. The session will only hold the last value of the loop.

A Session is a kind of variable that is attached to the current context and is available for the duration of the session.

When you read it back, you should cast the value back to its original value. However, it is important to know that it depends on what point of execution you are setting the session. If you are reading it back in before it is assigned, it won't work.

Rather think of creating extra string properties on your usercontrol that can be set using simple assignment. You can also assign other things, like Lists or Dictionaries, or whatever.

-- Abel --
0
 

Author Comment

by:westdh
ID: 24771532
that not the point I am not getting anything return from the session. So to make it more clear I put in the page load of one of the user controls this:

 sending Session --> Src="~/Modules/OrderSummary.ascx"

protected void Page_Load(object sender, EventArgs e)
        {
            this.ApplyLocalization();
            this.Session["uxQuantityText"] = "25";
        }

and in the reciever this : Src="~/Modules/WC_CompiliantControl.ascx

string t5 = this.Session["uxQuantityText"].ToString();

what I got was this error code

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 73:
Line 74:                string t4 = StateLabel2.Text;
Line 75:                string t5 = this.Session["uxQuantityText"].ToString();
Line 76:                string t6 = PeriodLabel2.Text;
Line 77:
 

Source File: c:\nopCommerce_1.21\NopCommerceStore\Modules\WC_CompiliantControl.ascx.cs    Line: 75
0
 
LVL 39

Expert Comment

by:abel
ID: 24771671
> Object reference not set to an instance of an object.
the usercontrol's load event comes before the load event of the page. Whenever you work with sessions, assume they can be null. The easiest way to share data between a usercontrol and its parent is not through sessions but through properties (getters/setters), this prevents hideous problems resulting from the complexity of the load order of controls in ASP.NET.

Whenever you work with sessions, use the following to prevent errors:

// old-style many people feel comfortable with:

string t5 = Session["uxQuantityText"] as string;   // using "as" prevents cast exceptions

if(t5 == null)

{

    t5 = "";

}
 

// new style since .NET 2.0

string t5 = Session["uxQuantityText"] as string ?? "";

Open in new window

0
 

Author Comment

by:westdh
ID: 24771824
Alright.. I got it to work with no errors, but also no data. I should see the number '25', so I am back to my original problem in that I cannot send to Memory or recieve from memory Session data.

Again I have treid  and found that I can send  & recieve Session's within a User control it self.

I am not the original developer of this application. It was written in VS2008. I have the source and want to modify it.

I do not know why Session do not work across user control or pages. The oriiginal soure also
passes session with a user control, but they do not attempt to pass Session across controls.
0
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

 
LVL 39

Expert Comment

by:abel
ID: 24771876
> Again I have treid  and found that I can send  & recieve Session's within a User control it self.
Sessions are nothing more then a StateBag (iirc) which means it is some sort of Dictionary style collection. It is indeed in memory, but you simply store values and retrieve them. If you retrieve them before you store them (i.e., when you store them in page_load and retrieve them in usercontrol_load) then it simply will not work. I cannot help the way usercontrols are supposed to be used, sorry about that.

> I do not know why Session do not work across user control or pages.
It does work across pages and it does work across usercontrols. It is, however, a dangerous thing to use if you are not sure when in the events timeline you set it. Try to read out the session in Request_Begin in global.asax to find out whether the session really is empty after you set it. If it is, you may have made a spelling mistake. Use copy/paste or global constants to prevent that.

I'd like to help you with the usercontrol's lifecycle, but that's a long and rather complex story. Once you've gone through it and the usercontrols are modified such that they behave like any other usercontrol, you'll find out that sessions are not the ideal way of moving data from pages to usercontrols (the reason is stated above, and is also one of "heavy coupling", which is dangerous in OO). Taking the 5 minute approach to resorting to properties will save you loads of troubles. But I can't make that decision for you, I can only point you in the right direction, the decision is of course entirely yours.

-- Abel --
0
 

Author Comment

by:westdh
ID: 24771938
Ok, then I''ll reort to Properties -->Taking the 5 minute approach to resorting to properties will save you loads of troubles.

Can you give me a Idea on how that works..
0
 
LVL 39

Expert Comment

by:abel
ID: 24772093
Inside your UserControl, add the following code snippet. After a recompile, you can then access your control's property using myUserControl.UsQuantityText = "something" from anywhere.

I used ViewState to save the data with the control.



public string UxQuantityText

{

    get

    {

        return (string) ViewState["uxQuantityText"] ?? "";

    }

    set

    {

        ViewState["uxQuantityText"] = value;

    }

}

Open in new window

0
 

Author Comment

by:westdh
ID: 24772360
This is what I have done so far. with your help. I belive i have a mistake  in defining this line

string t5 = Modules_WC_CompiliantControl.UxQuantityText;
                                                                      -----------------    redline

This looks ok
 public string UxQuantityText
        {
            get
            {
            return (string) ViewState["UxQuantityText"] ?? "";
            }
            set
            {
                ViewState["UxQuantityText"] = (TextBox)FindControl("txtQuantity") as TextBox;
            }
        }
0
 
LVL 39

Accepted Solution

by:
abel earned 500 total points
ID: 24773173
You got me lost a bit, where did you get the name Modules_WC_CompiliantControl from?

Suppose your user control is of type WC_CompiliantControl, then somewhere in your page's ASPX you have something like this:

<nopCommerce:WC_CompiliantControl runat="server" ID="myCompControl" />
Then, if you applied my code in your usercontrol, you could now do the following in your code behind of your page (but without first something assigned to it, this will be meaningless):

string t5 = myCompControl.UxQuantityText;
and you could do the following from within your ASPX, to set it from there using declarative syntax like so:

<nopCommerce:WC_CompiliantControl runat="server" ID="myCompControl" UxQuantityText="This Is Quantity Text"  />
-- Abel --

0
 

Author Closing Comment

by:westdh
ID: 31599518
You have been serving me well..I have not resolved it as yet..I guess I need to study it some more.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
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.

746 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

13 Experts available now in Live!

Get 1:1 Help Now