Solved

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

Posted on 2009-07-03
11
344 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
[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
  • 5
  • 5
11 Comments
 
LVL 9

Expert Comment

by:Rahul Goel ITIL
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
Independent Software Vendors: 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 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
 
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

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

732 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