Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare session variable in C#? [duplicate]

I want to make a new session, where whatever is typed in a textbox is saved in that session. Then on another aspx page, I would like to display that session in a label.

I'm just unsure on how to start this, and where to put everything.

I know that I'm going to need:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["newSession"] != null)
    {
        //Something here
    }
}

But I'm still unsure where to put everything.

like image 496
Carrie Avatar asked May 06 '13 21:05

Carrie


People also ask

How do you write a session variable?

Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user. The PHP code in the example below simply starts a new session.

How do you define a session variable?

Session variables are a way to store data about a user in a database and retrieve it later. Cookies are a way to store data about a user on the user's computer. Session variables are typically used in applications that need to keep track of a user's activity.

How do you use session variables?

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.


1 Answers

newSession is a poor name for a Session variable. However, you just have to use the indexer as you've already done. If you want to improve readability you could use a property instead which can even be static. Then you can access it on the first page from the second page without an instance of it.

page 1 (or wherever you like):

public static string TestSessionValue 
{ 
    get 
    {
        object value = HttpContext.Current.Session["TestSessionValue"];
        return value == null ? "" : (string)value;
    }
    set 
    {
        HttpContext.Current.Session["TestSessionValue"] = value;
    }
}

Now you can get/set it from everywhere, for example on the first page in the TextChanged-handler:

protected void TextBox1_TextChanged(Object sender, EventArgs e)
{
    TestSessionValue = ((TextBox)sender).Text;
}

and read it on the second page:

protected void Page_Load(Object sender, EventArgs e)
{
    this.Label1.Text = Page1.TestSessionValue; // assuming first page is Page1
}
like image 56
Tim Schmelter Avatar answered Sep 21 '22 17:09

Tim Schmelter