I'm with a problem and want to know if someone can help me.
I'm creating a table with some controls and I want to save all control values in every postback. As the controls are just defined after the page_load, I can't solve my problem this way:
object o;
protected void Page_Load(object sender, EventArgs e)
{
o = createObject();
Create_Table();
if (Page.IsPostBack)
Save_Data();
}
I thought I could execute Save_Data() at the begining of every postback event, but I think that should exist a better way to solve my problem.
Thanks.
Since you want it to be at the page level why not use ViewState? Since o appears to always be set with the same data there probably isn't need to set it more then once, though if you really want to you can remove the if not postback stuff...
protected object o
{
get {
return ViewState["o"];
}
set {
ViewState["o"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) { o = createObject(); }
Create_Table();
if (Page.IsPostBack)
Save_Data();
}
Your variable 'o' will not contain your original value once the postback is done. This is because each request creates a new page object on the server and your member variable values will be lost. It would be better to use the built in 'Session' property to save your data between requests.
See my answer here
Related
Hi I'm trying to save the values from the request.form after post back. I've tried to use viewstate on the input string but the page_load keeps regenerating the request.form
string TID = null;
Protected void Page_Load(object sender, EventArgs e)
{
if (TID == null)
{
TID= Request.Form ["totalID"];
}
Label1.Text = TID;
}
protected void Button2_Click (object sender, EventArgs e)
{
Label1.Text = TID;
}
Most asp.net controls have a text property, so if yours is a TextBox and you named it textBoxTotalID, then you can just get the value entered using this.textBoxTotalID.Text.
Instead of totalID, use the name of the element not the Id. The name is used for posting information to the server. And also make sure you have specified a name in your view for the element whose value you need on post.
In addition to that, ask yourself this question: Do you need to do that even when the user requests the page or only when the form is submitted? I am sure your answer is only when form is submitted. In that case, do it only when IsPostBack is true.
Try adding a check to the IsPostBack property.
if (IsPostBack)
{
//Set Values here
}
This is set to true when the page is responding to a post back from a form submit or perhaps a control event being fired.
I've just started learning ASP.NET and I'm facing a problem with getting textbox values. I want to do a simple calculator with only 4 basic operations but what happens is that after I click the + sign and click Go, I see that I didn't store the first number at all. Second number is fine though. Here is a sample of my code.
public partial class deafult : System.Web.UI.Page
{
public TextBox output = new TextBox();
public double temp,tempAdd, calc;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
tempAdd = Convert.ToDouble(output.Text);
output.Text = String.Empty;
}
//User enters another number after clicking Add button then clicks Proc
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
calc = tempAdd + temp;
output.Text = calc.ToString();
}
}
I debugged and tempAdd is always 0 but I get the number in temp. temp variables and calc is defined public.
You essentially have the problem with all of your variables being re-initialized on load of the page. Unlike winforms, web is stateless.
There are ways of persisting state between refreshes, however. The most obvious choice for your application would be to only go to the server once with the both values and what you want to do with them. ie One button click.
However, for personal edification, it may be worth looking up ViewState. This allows you to store values in an array of sorts and retrieve them even after a refresh.
There are also Session and Application level arrays in ASP.NET that work in similar ways.
Every time you call the page (by events) all your properties is initialized.
Try to do all your logic in one event or store your properties in manager / service / db.
In web (Asp.Net) on every postback properties will get cleared, try to use ViewState or Session variables to hold these values. Refer Asp.Net State Management concepts from MS.
Hope this may help you.
Web controls are State less so you should user session sate to hold the first value then do your stuff...
Ex:-
protected void btnAdd_Click(object sender, EventArgs e)
{
Session["tempAdd"] = output.Text;
output.Text = String.Empty;
}
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
string oldval=Session["tempAdd"] != null ?Session["tempAdd"].ToString() :"";
if(oldval!="")
tempadd=Convert.ToDouble(oldval);
calc = tempAdd + temp;
output.Text = calc.ToString();
}
I'm wondering what is my issue on passing a variable from page to page using asp.net session.
I've stripped the code down to just one text box to see whats going on. I'm just trying to take the value of a text box and display it on a confirmation page. When the button is clicked it transfers me to the second page but there label is blank. Yes my post back url is pointing to the second page.
Here is the button click:
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
}
Here is the page load of the second page:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = (string)(Session["name"]);
}
Unless I've been looking at this to long and missed something. I've already read "How to: Read Values from Session State" from MSDN.
You say that you've set the PostBackUrl to your second page. If you're going to do it that way, you need to use Page.PreviousPage to get access to your textbox. But this is the easiest way:
Firstly, leave the PostBackUrl alone. Setting the PostBackUrl to your second page means that you're telling the SECOND PAGE to handle your button click, not the first page. Hence, your session variable never gets set, and is null when you try to pull it.
This should work for ya.
And yes, you can also do this with a QueryString, but if its something that you don't want the user to see/edit, then a Session variable is better.
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
Response.Redirect("PageTwo.aspx");
}
Then in the second page (You don't REALLY need the ToString()):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
lblName.Text = Session["name"].ToString();
}
}
EDIT -- Make sure that your button click actually gets fired. Someone can correct me wrong on this, as I do most of my work in VB.NET, not C#. But if you don't specify the OnClick value, your function won't get called.
<asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="submit_Click" />
The code you have posted looks fine, so your problem is probably with setup.
Check this link ASP.NET Session State Overview and pay particular attention to the sections on Cookieless SessionIDs and Configuring Session State.
I don't think you added the session. This is how I have done mine.
First Page
protected void btnView_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbxCheckDates.Items)
{
if (li.Selected == true)
{
lblMessage.Text = "";
string checkDate = lbxCheckDates.SelectedItem.Text;
Session.Add("CheckDates", checkDate);
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('Paystub.aspx','_newtab');", true);
}
}
}
Second Page
protected void Page_Load(object sender, EventArgs e)
{
string checkDate = (string)(Session["CheckDates"]);
//I use checkDate in sql to populate a report viewer
}
So with yours, I think you need..
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session.Add("Name", name);
}
I think what you have in the second page should work, but if it doesn't, add ToString() to it like..
lblName.Text = (string)(Session["name"]).ToString();
Let me know if this helps!
Are you doing a redirect after setting the session variable on the first page, if so you it will not work correctly (unless you know the trick). Checkout this article on making it work. Basically, the way to make this work is to the overload redirect method.
Response.Redirect("~/newpage.aspx", false);
The false parameter prevents .net from terminate processing on the existing page (that actually writes out the session state)
For Second Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value"] != null)
{
Label1.Text = Session["value"].ToString();
}
else
{
Label1.Text = "Sorry,Please enter the value ";
}
}
You can use Server.Transfer() instead of Response.Redirect()
For first page, use this:
protected void Button1_Click(object sender, EventArgs e)
{
string value = TextBox1.Text;
Session["value"] = value;
Response.Redirect("~/Sessionpage.aspx");
}
Whenever i click on the Button1 repeatedly then text in the Literal1 is not incremented. Can you please tell me reason?
Expected: value show in text field increment after every button click.
Current result: value always shows 1.
public partial class d1 : System.Web.UI.Page
{
int c;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
c = 1;
Literal1.Text = c.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
c=c+1;
Literal1.Text = c.ToString();
}
}
The reason is that c is an instance variable on that class. And each post-back to the server creates a new instance of the class. So c is being initialized to 0 on each post-back. If you want c to persist outside of a single instance of that class, you need to store it somewhere. Session, application, a database, etc. (Specifically where depends on under what circumstances the value of c should persist. I'm guessing this is just test code to get a feel for the functionality, so you might try all of the above and see how they differ.)
For a lot more information on this, you'll want to read up on the ASP.NET Page Life Cycle.
Essentially, "global" doesn't describe c very accurately as a variable. It's scope is very limited to only that class, and more specifically only to any one instance of that class.
I have a web user control that holds three dropdownlists: One holds days, second holds months and the third one holds years. Days and months are static.But year items will change upon need to avoid entering wrong year. Let me first list here what I do in order, then i'll ask my question:
I have a private int yearSpan.
In private method PopulateYearList I say:
int year = DateTime.Now.Year;
int span = year - this.yearSpan;
for (int i = span; i <= year; i++)
{
ddlYears.Items.Add(i.ToString());//Here I get NullReferenceException
}
I've overriden the default constructor to receive yearSpan as an argument:
public DatePicker(int yearSpan)
{
this.yearSpan = yearSpan;
this.PopulateYearList();
}
Now, as you might have guessed in my PopulateYearList method I get NullReferenceException because I try to add an item to ddlYears that has not been constructed yet. What would you suggest to do to solve this?
don't call this.PopulateYearList in constructor, rather call it on Load event of user control.
Also I prefer you to not use constructor of your user control rather use public property as it can maintain its state.
e.g. in Page:
protected void Page_Load(object sender, EventArgs e)
{
UserControl1.TimeSpan = DateTime.Now.Year;
}
In UserControl:
protected void Page_PreRender(object sender, EventArgs e)
{
if(this.IsPostBack)
{
PopulateYearList()
}
}
As long as you don't make any change to that control from your parent page, any event after your controls are load , you can call this.PopulateYearList. I called it in PreRender event as if somebody changed the value from page it would be overriden by user control value at the end, thus I am sure my values are not tempered.
Let me know if I am missing something.
Ether call the PopulateYearList in the Page_Load of your usercontrol. Like this:
protected void Page_Load(object objSrc, EventArgs e)
{
if(this.IsPostBack)
PopulateYearList()
}
Or make the PopulateYearList public and call it on the page when you bind the page controls