murday1983 murday1983 - 23 days ago 7
C# Question

Retrieve Data From Previous Page

I have a website which stores data in a session and on the 3rd page displays the entries entered on pg1 & pg2.

But on pg2, there is a back button but when it's clicked I don't know how to re-display the entry entered as its lost.

I'm new to using session storing so I may be doing something completely wrong so please advise me if I am.

Anyway my code is:

Pg1 HTML

<form id="form1" runat="server">
<div>
<p>pg1</p>
<asp:TextBox ID="txtData1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="pg1button" runat="server" Text="Submit" OnClick="pg1button_Click" />
</div>
</form>


Pg1 code behind

protected void pg1button_Click(object sender, EventArgs e)
{
Session["pg1"] = txtData1.Text;
Response.Redirect("/Session/pg2.aspx");
}


Pg2 HTML

<form id="form1" runat="server">
<div>
<p>pg2</p>
<asp:TextBox ID="txtData2" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="pg2button" runat="server" Text="Submit" OnClick="pg2button_Click" />&nbsp;
<asp:Button ID="pg2Backbutton" runat="server" OnClick="pg2Backbutton_Click" Text="Back" />
</div>
</form>


Pg2 code behind

protected void pg2button_Click(object sender, EventArgs e)
{
Session["pg2"] = txtData2.Text;
Response.Redirect("/Session/pg3.aspx");
}

protected void pg2Backbutton_Click(object sender, EventArgs e)
{
Response.Redirect("/Session/pg1.aspx");
}


Pg3 HTML

<form id="form1" runat="server">
<div>
<h1>Session State</h1>
<p>Pg 1 data is: <%=Session["pg1"] %></p>
<p>Pg 2 data is: <%=Session["pg2"] %></p>
</div>
</form>


Everything is working as it should except my back button. The reason for using session is that the website doesn't use a DB as the third page will have (when I get round to it) a button which will email the details to a specified email address.

I have had to strip out some parts of the HTML due to company policy so its the bare basics given, sorry.

Answer

Add the below logic inside your pg1.cs file

 protected void Page_Load(object sender, EventArgs e)
 {
     if (txtData1.Text == string.Empty && Session["pg1"] != null)
      {
         txtData1.Text = Session["pg1"].ToString();
      }
  }

--SJ