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();
Related
I have many aspx pages which are a process to create a final form. eg,
Select Item Type Page -> Select item color page -> Select item quantity page -> Complete Page
Each page have a next and a previous button and when I move from the first page to the second page and the user clicks the previous button returning to the first, the control's states will be reset losing all the user's input
I thought of saving the controls in a session this way:
protected void btn_Next_Click(object sender, EventArgs e)
{
if (validateForm() == true)
{
Session["test1"] = RadioButtonList1;
Response.Redirect("nextpage.aspx");
}
}
And loading it this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["test1"] != null)
RadioButtonList1 = (RadioButtonList)Session["test1"];
getInfo();
}
}
However, I selected the 2nd item in the radiobuttonlist1 and when i move to the 2nd page and back to the 1st, it didn't load the exact state of the radiobuttonlist1. The debugging shows it went into the RadioButtonList1 = (RadioButtonList)Session["test1"]; code
Can you try this :
Set the value attribute for each list-item and retrieve the selected value in a session like this
Session["test1"] = RadioButtonList1.SelectedItem.Value;
and while loading
RadioButtonList1.SelectedValue = (String) Session["test1"];
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();
}
I have a ddl on my master page that is set to auto postback to retrieve data based on their selection. The values in the list are customerids and they have been setup as a session variable and once someone has selected which one, the code looks at session["selectedCustomer"] and populates the appropriate fields. Now the problem that I have run into, is when the auto postback goes through on Chrome or IE, it populates the fields and then the selected customer is set back to default which is "Please select customer" which has no value behind it. In firefox after the postback it populates the fields and then the drop down list stays on the selected customer.
protected void ddlSelectedCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
CustomerSelected();
Response.AppendHeader("Refresh", "0; URL=" + this.ResolveUrl("~/AcesSetup/storefront.aspx"));
try
{
ViewState["SelectedAccordionIndex"] = ((AjaxControlToolkit.Accordion)FindControl("MyAccordion")).SelectedIndex;
}
catch (Exception ex)
{ }
}
That is the selectedChanged event for my ddl
private void CustomerSelected()
{
//clear the session variable
Session.Remove("selectedCustomer");
//user selected customer
if (ddlSelectedCustomer.SelectedIndex != -1)
{
Session["selectedCustomer"] = ddlSelectedCustomer.SelectedValue;
}
}
private void fillCustomers()
{
//save the value of the current selection to reselect later if still exists
string origSelectedItem = ddlSelectedCustomer.SelectedValue;
//check what role the user is in
string usersRole = Roles.GetRolesForUser(Membership.GetUser().UserName)[0];
MembershipUser user = Membership.GetUser();
switch (usersRole)
{
case "SalesRep":
ddlSelectedCustomer.DataSource = DAL.Util.getSalesRepCustomers((Guid)user.ProviderUserKey);
ddlSelectedCustomer.DataBind();
break;
case "BasicUser":
case "Customer":
ddlSelectedCustomer.DataSource = DAL.Util.getCustomersListForUser((Guid)user.ProviderUserKey);
ddlSelectedCustomer.DataBind();
break;
case "Admin":
case "SuperAdmin":
ddlSelectedCustomer.DataSource = DAL.Util.getAllCustomersList();
ddlSelectedCustomer.DataBind();
break;
default:
break;
}
//if user had a company selected, reselect it if it exists
if (origSelectedItem != string.Empty)
ddlSelectedCustomer.SelectedValue = origSelectedItem;
else if (ddlSelectedCustomer.Items.Count == 1)
{
//if only one item in the list, select it
ddlSelectedCustomer.Items[0].Selected = true;
}
This what populates the drop down list. Also when Firefox does the post back the whole page does not appear to reload, with Chrome or IE the whole page will flash white and reload.. That to me seems like it has something to do with it. Because with Firefox the viewstate I have for my accordion works like it is supposed to, but again not with Chrome or IE.
If you have any help I would appreciate it, if there is anything I can clear up, or any code snipets I could provide I will do my best to update everything.
Thank you.
protected void ContentPlaceHolder1_Load(object sender, EventArgs e)
{
if (Session["selectedCustomer"] != null)
{
ddlSelectedCustomer.SelectedValue = Session["selectedCustomer"].ToString();
}
}
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" OnLoad="ContentPlaceHolder1_Load">
</asp:ContentPlaceHolder>
You don't lose the session , you just clear the selection .so try to handle the Load event of your ContentPlaceHolder by setting the selected value by the stored session.
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;
}
i have a alphabetic filter consist of 26 dynamically created link button on selecting any link button it is filtering the name of user's on the basis of alphabet and changing its color to orange to make it different from other linkbuttons it is working fine but if there are more number of user associated with a particular alphabet and on applying filter it is filtering the user on the basis of that alphabet and showing them in a list view on clicking the data pager next page or any other page number the link button changes its color to default color but i want to keep that highlighted until and unless other link button is selected
my code
protected void Page_Init(object sender, EventArgs e)
{
// Adding Dynamically linkbuttons for all alphabets(i.e. A-Z)
for (char asciiValue = 'A'; asciiValue <= 'Z'; asciiValue++)
{
LinkButton lbtnCharacter = new LinkButton();
lbtnCharacter.ID = "lbtnCharacter" + asciiValue;
divAlphabets.Controls.Add(lbtnCharacter);
// Setting the properties of dynamically created Linkbutton.
lbtnCharacter.Text = Convert.ToString(asciiValue);
lbtnCharacter.CssClass = "firstCharacter";
lbtnCharacter.ToolTip = "Show Tags starting with '" + Convert.ToString(asciiValue) + "'";
lbtnCharacter.CommandArgument = Convert.ToString(asciiValue);
lbtnCharacter.Command += new CommandEventHandler(lbtnCharacter_Command);
}
}
// For assigning default color to linkbutton text in page load
foreach (var ctrl in divAlphabets.Controls)
{
if (ctrl is LinkButton)
((LinkButton)ctrl).CssClass = "firstCharacter";
}
void lbtnCharacter_Command(object sender, CommandEventArgs e)
{
// Storing the values of pressed alphabet in viewstate.
ViewState["Selected_Character"] = e.CommandArgument;
LinkButton lbtnSelected = (LinkButton)divAlphabets.FindControl("lbtnCharacter" + e.CommandArgument);
lbtnSelected.CssClass = "firstCharacter highlighted";
txtTagFilter.Text = string.Empty;
BindTagList();
}
I hope I understood your question.
You are setting your Selected_Character item in the command handler and then setting the class of the button to highlight it. This only gets fired when the button is clicked, not when you move to the next page. Why not separate these two operations. Set the class of the link button on prerender if the Selected_Character matches. That way even when you page the link button will stay highlighted.
I would also set your selected character as a query string parameter, if someone copies and pastes a link to your page the button would not highlight and the correct data would not display.
Hope this helps.
Edit: Haven't tested the below but maybe it will get you started.
void lbtnCharacter_Command(object sender, CommandEventArgs e)
{
// redirect to self with tag as qs parameter
Response.Redirect(string.Format("{0}?tag={1}", Request.Url.GetLeftPart(UriPartial.Path), e.CommandArgument));
}
protected void Page_PreRender(object sender, EventArgs e)
{
if (Request.QueryString["tag"] != null) {
LinkButton lbtnSelected = (LinkButton)divAlphabets.FindControl("lbtnCharacter" + Request.QueryString["tag"]);
lbtnSelected.CssClass = "firstCharacter highlighted";
}
}
N.B You will also need to change your BindTagList to use the query string also. I'm assuming you call this in the page load event.