using sessions in asp.net
-
23-08-2019 - |
Question
I would like the data that i enter in a text box on pageA to be accessable on pageB
eg: User enters their name in text box on page A
page B says Hello (info they entered in text box)
I heard this can be accomplished by using a session but i don't know how.
can someone please tell me how to setup a session and how to store data in it? Thank you!
Solution
Session["valueName"]=value;
or
Session.Add("valueName",Object);
And You can retrieve the value in label (for Example) By
/*if String value */
Label1.Text=Session["valueName"].ToString();
or
Label1.Text=Session.item["valueName"].ToString();
And also You can remove the session by;
/*This will remove what session name by valueName.*/
Session.Remove( "valueName");
/*All Session will be removed.*/
Session.Clear();
OTHER TIPS
// Page A on Submit or some such
Session["Name"] = TextBoxA.Text;
// Page B on Page Load
LabelB.Text = Session["Name"];
Session is enabled by default.
Yes, you could do something like JohnOpincar said, but you don't need to.
You can use cross page postbacks. In ASP.Net 2.0, cross-page post backs allow posting to a different web page, resulting in more intuitive, structured and maintainable code. In this article, you can explore the various options and settings for the cross page postback mechanism.
You can access the controls in the source page using this code in the target page:
protected void Page_Load(object sender, EventArgs e)
{
...
TextBox txtStartDate = (TextBox) PreviousPage.FindControl("txtStartDate ");
...
}
You can use session to do this, but you can also use Cross Page Postbacks if you are ASP.NET 2.0 or greater
http://msdn.microsoft.com/en-us/library/ms178139.aspx
if (Page.PreviousPage != null) {
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null) {
Label1.Text = SourceTextBox.Text;
}
}
There is even a simpler way. Use the query string :
In page A :
<form method="get" action="pageB.aspx">
<input type="text" name="personName" />
<!-- ... -->
</form>
In page B :
Hello <%= Request.QueryString["personName"] %> !