C# how to retain values after redirecting - c#

So what i want to know is that how do i retain the values after redirecting, where after clicking the back button brings me back to the first page. For example, if i store some values in page 1 then i click submit, which brings me to page 2. But in page 2 i want to click back. How do i retain the values that i have submitted in page 1?
Also, what must i write in the btn_Click field? This is my code? What should I change
protected void btnBack_Click(object sender, EventArgs e)
{
Server.Transfer("AddStaff.aspx", true);
Response.Redirect("AddStaff.aspx?" +strValues);
}

there are several ways you can retain the value.
Using Cookie
Using Session
Using Query String
Using database
For example let's look at how to set the Cookie
HttpCookie cookie = new HttpCookie("ValueToSave", "StackOverFlow");
Response.Cookies.Add(cookie);
Response.Redirect("~/WebForm2.aspx");
To Access the Cookie you can do as follows on Page_Load
if (Request.Cookies["ValueToStore"] != null)
{
string tempCookie = Request.Cookies["ValueToStore"].Value;
}
Using session you can achieve it as follows
Save value to Session on Button Click
Session["ValueToStore"] = "StackOverFlow Session";
Retriving the value on Page Load
if (Session["ValueToStore"] != null)
{
string val2 = Session["ValueToStore"].ToString();
}

Related

value of asp:textbox is not being changed after written over it

I have a text box like this:
<asp:TextBox runat="server" ID="reasonNameTextBox"></asp:TextBox>
when I load the page in the first time, i put a value inside it like this:
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
Then, the user can enter his new value, and click save button.
My problem
when the user clicks save button, the value of the text box is still the value that I assigned when the page is loaded, not the value the the user has written.
I tried to use Google Chrome F12 feature, and I found the error.
Please look at this image
as you see, the value that i wrote in the text box is New Value, however, the value in the text box (when using F12) is still s, where s is the value that I assigned when the page is loaded.
why is that please?
The is because every time you are clicking on the button you are posting back and the page is again reloaded, Thus calling Page_Load, Which in turn is assigning the value you have assigned during page load.
To avoid this you need to do something like this :-
If(!IsPostback)
{
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
This, wouldn't update your textbox value with defaultvalue you have set during Page_Load and will take user updated value.
Changing the value doesn't update the DOM (unless you change it via javascript). So inspecting the textbox via developer tools, as you did, yields the text value you received from your server.
The interesting part lies in your WebPage's CodeBehind file. I assume it looks similar to this:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var results = GetResults();
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
}
In this case the textbox's value will be set every time, regardless of the user-input. What you have to do, is look for a postback:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var results = GetResults();
if (IsPostBack)
{
// retrieve the user input
var input = reasonNameTextBox.Text;
}
else
{
// set default value
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
}
}

Open webform from GridView to add record to SQL table. C#

I'm not sure how to go about this. I am able to pass the Primary key value from the selected row in a GridView to the next page using Response.Redirect, but I need to populate a couple other fields from that row too. Here is what I have. I want to know if I can set another textbox equal to a value using the primary key value, that was passed from the previous page.
protected void Page_Load(object sender, EventArgs e)
{
string dataKey = Request.QueryString["id"];
ProjNo.Text = dataKey;
}
Not altogether clear what you are trying to to do but i can make some observations. Once you are on the new Webform all the context from the original request has gone unless you have saved it somewhere at the time of the Response.Redirect(). You have a few options, putting it into the querystring:
Response.Redirect("/page.aspx?id=" + id + "&field1=" + field1);
You could just save it in the session:
HttpContext.Current.Session["field1"] = field1;

how to redirect to another page and move the content

I have a page with a lots of elements in it.
I want to let the user press a button and then page redirected and the contents of the div inserted into the HTML Editor which I have.
Thanks in advance
Add a public property to your source page. Add runat=server and an id to your div.
public String HtmlContent
{
get
{
return div.InnerHtml;
}
}
Add virtual path of your source page to your editor page.
<%# PreviousPageType VirtualPath="~/source.aspx" %>
You need to redirect from your source page with using Server.Trasfer method.
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("editor.aspx");
}
Finally in your editor page you can pass the values to your Html Editor.
if (PreviousPage != null)
{
string innerHtml = PreviousPage.HtmlContent;
}
You can achieve something like that with Cross-page posting in ASP.Net.
You may want to consider storing the data into a database and then just passing the id of the record to the new page as a query parameter; then on your redirected page, read the data out of the database using the id passed in

problem with linq to sql update using asp.net textboxes

I have a textbox and a button. On page load I select one column from one row and put its value in the textbox. I have a button click method that updates the same column/row with the value in the textbox.
The problem i'm having is that when I clear the text in the text box, type in new data and hit submit the new text value is not being saved, it uses the old one.
I put a breakpoint at the end of my button click method and it appears that asp.net is sending the old value of the textbox rather than the new one I put in. I'm totally stumped.
This problem persists even if I have viewstate false on the textbox.
Both of my LINQ queries are wrapped in a using statement.
Any Ideas?
Edit: Here is the full code:
protected void Page_Load(object sender, EventArgs e)
{
using (StoreDataContext da = new StoreDataContext())
{
var detail = from a in da.Brands
where a.BrandID == 5
select new
{
brand = a,
};
foreach (var d in detail)
{
txtEditDescription.Text = d.brand.Description;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (StoreDataContext dk = new StoreDataContext())
{
Brand n = dk.Brands.Single(p => p.BrandID == 5);
n.Description = txtEditDescription.Text;
dk.SubmitChanges();
}
}
As you said, in Page_Load you are retrieving the original value into the text box which overwrites any changes.
Yes, Page_Load DOES execute before Button Click (or any other control events) is executed. I'm going to guess you have done Windows Forms development before this, the ASP.Net web forms event model is quite different. Check out the ASP.NET Page Life Cycle Overview.
I figured it out. I should be be using if(!IsPostBack) on the code that originally fills the textbox with its value.
However this makes no sense to me. If the page is loaded and the textbox text gets a value, then you clear this value and try to insert it into the database, it should insert this value and then when the page post back it will fetch the new value from the database and put the value in the textbox.
The way it's actually working makes it seem like it is executing the page load code before the button click code is executed on post back.
just to trace the error,please try to put a label =( lblDescription.Text ) and leave the rest of code as is,put the new value in the textbox (editdescription.text) try it and tell me what you see
foreach (var d in detail)
{
lblDescription.Text = d.brand.Description;
}

back to the previous page with values still present in textboxes

I have a start page with textboxes and I am sending the values entered in the textbox to another page using Cache on click of a next button.
Now I have a problem that when the user goes to the next page ad decides to go back again he should be able to do so and the values he entered in the textboxes should still be present.
Is there a way to do so...
My code for sending values is:
protected void Button4_Click(object sender, EventArgs e)
{
if (TextBox2.Text == "" || TextBox3.Text == "")
{
Label1.Text = ("*Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
Cache["PolicyName"] = TextBox2.Text;
Cache["PolicyDesc"] = TextBox3.Text;
Response.Redirect("~/Addnewpolicy3.aspx");
}
}
and I receive this by on the next page as:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string pn = Cache["PolicyName"].ToString();
string pd = Cache["PolicyDesc"].ToString();
string os = Cache["OperatingSystem"].ToString();
}
}
It sounds like you want to take adavantage of Cross-Page postbacks which were added to ASP.NET in version 2.0
The following URL should offer some guidance
http://msdn.microsoft.com/en-us/library/ms178139.aspx
Cache is shared by all users. The code above will result in information being shared between users. If you want per-user temp storage you should use the Session instead. Other than that I can make 2 recommendations:
Proceed with Session, your approach is fine
Look at the Wizard control http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
To make the values restore, in the controls simple do this:
<asp:TextBox ID="txtName" runat="server" text='<%=Session["Name"] %>'></asp:TextBox>
Pretend you got two pages, page1 and page2:
1st you search on page1 and get the result, then click into the link and enter 2nd page.
My suggestion is when you click on hyperlink/button on page1, you can put the textbox field value into session like
Session["key"] = txtbox.Text;
After you enter 2nd page, you can try to set session equal to itself in "Back" button action for bring back to page1.
Session["key"] = Session["key"].ToString();
Insert the code when you back from page2, get value from session and put into search form's textbox
txtbox.Text = Session["key"].ToString();

Categories

Resources