aspguy
aspguy

Reputation:

using sessions in asp.net

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!

Upvotes: 2

Views: 3253

Answers (5)

Andrei Rînea
Andrei Rînea

Reputation: 20800

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"] %> !

Upvotes: 0

Bob
Bob

Reputation: 99824

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;
    }
}

Upvotes: 0

eKek0
eKek0

Reputation: 23329

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 ");
    ...
}

Upvotes: 1

Syed Tayyab Ali
Syed Tayyab Ali

Reputation: 3681

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(); 

Upvotes: 5

JohnOpincar
JohnOpincar

Reputation: 5823

// 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.

Upvotes: 4

Related Questions