简体   繁体   中英

Cookies and session state in asp.net

I want to take the name the user types in and then display this on another aspx page using session state.

On the page where to user types the name the code I have is

Session["name"] = TextBox1.ToString(); //Store the session state in a variable called name from the text box.

Response.Redirect("page2.aspx");

Now on page2.aspx I have tried calling this variable but nothing seems to work.

I have a empty label1 on the page so I want the name to be stored into the empty label

Label1 = Session["name"];

The error message is convert type object to System.Web.UI.WebControlers.Label

Session["name"] = TextBox1.Text.ToString();    

Label1.Text = Session["name"].ToString()

There are two errors: first, you've tried assigning the Label1 variable, rather than the label's text, hence the error you got. Session[key] returns object , while Label1 is of type System.Web.UI.WebControlers.Label

The second one - you've set the value to user session value and tried accessing it via username variable.

Session["username"] is object type and could not be assigned to label with implicit cast. You would have a string in Session["username"] and calling ToString() will give that then you can assign username to label text property.

Label1.Text = Session["username"].ToString();

It is better to do this since it won't throw an exception if value is null:

Label1.Text = (string)Session["username"];

If you are sure that username is set than you can do this:

Label1.Text = Session["username"].ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM