I have the following project :
It's a page that on Page_Load it fills a TextBox named Email and a TextBox named UserName with a value obtained from asking a database.
Then there is this button, if the email is not null(user is not registered) it will let you register, otherwise it will let you change the email linked to your username.
The thing is, when trying to modify the email, doing an update query, the page preloads, taking the new value placed on Textbox Email the same that is retrieved from the database, making so it will never change.
I've tried to see if it executes the query and it does.
I've tried everything, keeping the variable on a hidden label, creating two different buttons with no luck as when it reloads the code those values are empty again.
I was thinking if I could keep the variable somehow that isn't cookies.
I think You know What is happening.. On every Post back the Page_Load event resetting your Textbox Value
Use IsPostBack to bind the value only on 1st load of page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind dropdown and fill textbox here
TxtName.Text = "Your values";
GetDropdowns();
}
}
I hope this will solve your issue
I totally agree with Kanis XXX, you can use IsPostBack to fill the values only at the start page, and not on other postbacks. In my experience, there are some other advices for your problems:
Using Viewstate, Session state,... to keep your working variable. You can have more detail here: https://kimphuc.wordpress.com/2009/10/18/the-difference-between-viewstate-sessionstate-cookies-and-cache-in-asp-net/
Try to use UpdatePanel, this could be useful in some cases, let you refresh or update data just a part of your page, not the whole page. https://msdn.microsoft.com/en-gb/library/bb398864%28v=vs.100%29.aspx
Related
I'm writing code to read data from asp controls to update records in a database. I've been debugging the last day and I've tracked it back to something that I ought to have noticed before.
The code first populates the controls with the existing values from the database.
When I click SAVE, it should read the current values from the controls and save with those.
Unfortunately, what it's actually doing is using the values of the controls before a change was made to them. It's not seeing the change to the controls.
Here's a sample:
<asp:TextBox ID="OtherCourseName_5" runat="server"></asp:TextBox>
Here's the corresponding behind code in the btnSave_onClick() function:
int object_number=5;
string other_course_name_string
= "OtherCourseName_" + object_number.ToString().Trim();
TextBox ocn = utilities
.utils
.FindControlRecursive(this.Master, other_course_name_string) as TextBox;
I'm using the FindControlRecursive() I found somewhere on the web. It works, I'm sure, but just in case, I tried to address the control directly as OtherCourseName_5.Text.
Even if I just display the value in OtherCourseName_5.Text, it gives the original value.
I use this same page for both entering new data and for editing data. It works fine when I enter the data. That is, it correctly sees that the TextBox control has changed from empty to having data. It's only when I invoke the edit function on the page (by passing edit=true). I invoke it this way by adding the switch edit=true as a query string (the program correctly reads that switch, gets to the appropriate area of code, prints out all the correct values for everything - except the contents of the controls!).
The page is far too complicated to post the entire thing. I've tried to convey the essential details. It's entirely possible that I've made a simple coding error, but it's seeming more a possibility that I fundamentally misunderstand how pages are processed.
Is there anything known that can make it seem as though the value of a control has not been changed?
Note 1: I thought perhaps I had to go to another field after I entered the data, but I tried that and it's still a problem.
Note 2: I'm using both TextBox and DropDownList controls and have the same problem with both.
Note 3: These controls are on a panel and the page is using a SiteMaster. I haven't had any problem with that and don't think the problem is there, but I'm down to questioning the laws of the physics at this point.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate controls with data from database
}
}
When you do a postback before the postback handler is evaluated the PageLoad event is raised
so if you don't avoid to rebind your control they will be loaded with the values from the database. And then the postback event will save them to db
Asp.net Page Lifecycle
(source: microsoft.com)
I am working on an Asp.net, C# Application.
I want to Refresh the webpage after I clicking on “Update” LinkButton; in Grid view. I have tried the following code; however it just refreshes the page without saving the updated data in Grid view.
protected void LinkButton1_Click1(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl.ToString());
}
Name of DataSource SqlDataSourcePlan
SELECT [PlanID], [Deposit], [DepositReturn], [Discount] FROM [PaymentPlan] WHERE ([Ref] = #Ref)
UPDATE [PaymentPlan] SET [Deposit] = #Deposit, [DepositReturn] = #DepositReturn, [Discount] = #Discount WHERE [PlanID] = #original_PlanID
Use RawUrl instead:
Response.Redirect(Request.RawUrl)
The raw URL is defined as the part of the URL following the domain
information. In the URL string
http://www.contoso.com/articles/recent.aspx, the raw URL is
/articles/recent.aspx. The raw URL includes the query string, if
present.
Edit: "without saving the updated data in Grid view"
Why do you think that redirecting the page to itself should save something somewhere?
Have a look at this tutorial: Inserting, Updating, and Deleting Data with the SqlDataSource (C#)
I assume that you actually want to update the GridView instead of the whole page. Then you should call GridView.DataBind().
My guess (without some other informations in the code it is difficult to say) is that althought the information is saved in the database, the datasource for the gridview is not refreshed with the new values.
I have seen this problem often regarding this part.
You have to rebind the gridview with Page.DataBind or GridViewName.DataBind() (where GridViewName is the name of your gridview) before the redirect.
You probably don't reload the GridView at PageLoad or PageLoad does not occure (can't know without the server code). If that would work properly, you would not need the databinding before redirecting.
I wrote a ASP.NET Application and it run in IIS7 of a Server. If I open this webform in my Browser and show me the Sitecode I see this...
I have many Controls how Buttons,Labels,TextBoxes and a ListView. I try to deactivate ViewState in the web.config but if I deactivate this my Application don't run correctly. What can I do?
Deactivate only the controls that not need the viewstate.
To do that you need to understand what the viewstate is.
Viewstate is where the page save and remember the values of the controls to have them after a post back. Remember that, the viewstate is used after a post back.
So actually you have two times the same data, but only the viewstate is post back the previous data and code behind can be use that data.
So the main question is, what controls do you need to be remember what you have fill them in, or what controls need to remeber the previous state of them.
Lets see a simple Literal with EnableViewState on and off.
ViewState ON
<asp:Literal runat="server" EnableViewState="true" ID="txtLiterar">
Now if you place a text on this literal the text is also saved on viewstate and on code behind you can do that.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtLiterar.Text = "Hello There";
}
}
So after the post back the Literal still have its content, and you can avoid to fill it again, because the viewstate have it and automatically fills it again.
ViewState OFF
<asp:Literal runat="server" EnableViewState="false" ID="txtLiterar">
Now if you place a text on this literal the text is not saved on view state and on code behind you add it as.
protected void Page_Load(object sender, EventArgs e)
{
txtLiterar.Text = "Hello There";
}
So the different is that you need to always fill that control with data on every post.
Where the viewstate is needed most.
The most needed part of the viewstate is when you fill a dropdown list. There you have a databind and code behind need to remember the values to place on the SelectValue the correct one.
Its also needed on GridView and other controls like that because is keep the previous page and other information's when you paging your data.
So you can close on most of your controls the viewstate - on that controls that you can fill them again on every post back, and on that controls that not need to remeber the previous state.
More to read:
How to optimize class for viewstate
Determine size of ASP.NET page's viewstate before serving page
Limiting view state information on AJAX calls
What I'm trying to achieve/plan, is whereby a page loads with a set of inputs, e.g. TextBox, Radio List etc. Taking TextBox as an example, there is a button for the user to "Add" another textbox to the page (in the same group), e.g. Member1, Member2, Member3 etc etc.
Two questions:
I could add these with Javascript, however the resultant "save" on postback would not get these inputs? If so, how?
The form needs to work without Javascript as well, so postback to dad another control is fine, however if I click the "add" button again, it will only ever add one control.
protected void btnAdd_OnClick(object sender, EventArgs e)
{
holder.Controls.Add(new TextBox { ID = "txtControl1" });
}
You can access the dynamic controls in the postback by name, using the following syntax "Page.Request.Form[""].ToString();". This uses the "name" attribute, not the "id" attribute.
I guess you can have one of these scenarios :
1- to save any new control ( textbox ) data in a session variable .. for example save name and value in which when any post back you can draw then again from this variable
2- If the only post back done from Add button you can do its function without doing post back as in this example http://msdn.microsoft.com/en-us/library/ms178210.aspx
So I am experiencing an issue with an .aspx page and some server side code, where I am getting unexpected results.
The goal of this page is simple, there are 5 radio buttons and a button with a server side onclick function. The idea is the user picks 1 of the 5 radio buttons, and then clicks the button. Upon clicking the button I verify (not using form validation, because I wanted a different feel) that a button is checked, and then store the selected option in a database.
Due to the fact that the number of radio buttons may change in the future I decided to try and abstract the number of radio buttons to make it easier on my self to change in the future.
So at the top of my server side code I created a list of possible options.
I then have a registerVote function that takes in a RadioButton object, and a number to grab a setting from the config file. I throw those 2 values into a wrapper class, and then add them to the list of possible options.
Finally when the submit button is pressed, I iterate through all possible options to see which one is checked, and grab its associated value.
public partial class VotePanel : System.Web.UI.Page
{
List<VoteOption> voteOptions = new List<VoteOption>();
public string registerVote(RadioButton newRadioButton, int voteOption)
{
voteOptions.Add(new VoteOption(newRadioButton, voteOption));
return ConfigurationManager.AppSettings["vote_option_" + voteOption];
}
protected void Submit_Click(object sender, EventArgs e)
{
//Check vote
string vote_value = "";
bool someButtonChecked = false;
foreach (VoteOption vo in voteOptions)
{
if (!someButtonChecked && vo.button.Checked)
{
vote_value = vo.movie;
someButtonChecked = true;
}
}
//....
}
}
class VoteOption
{
public RadioButton button;
public int vote_value;
public VoteOption(RadioButton r, int v)
{
button = r;
vote_value= v;
}
}
The code I use in page to add a radio button looks like this
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Vote" style="position: relative; top: 3px;" /><%=registerMovie(RadioButton1,1)%>
Now for the problem I am experiencing. Whenever the submit button is clicked, the list has a count of zero, and looks like it has been reinitialized. I validated that values are being added, by returning the list count in the registerVote method, and objects are indeed being added, but for some reason are not available to the Submit function.
Now variables on a page like this shouldn't reinitialize right? I also tested a string, and it did not reset and was available to the Submit button. What I did was define a class variable string time = DateTime.Now.Ticks.toString(); and displayed that after the submit button was clicked, and the time was always the same reguardless of how many times I clicked it.
So why would my List reinitialize, but not a string? Any ideas?
Keep in mind that your page class will be constructed and destructed for every request - no state will be maintained between each page load, it is up to you to properly recreate state as needed. In this case it appears that your list voteOptions is not being recreated before Submit_Click is called.
You'll have to register all your voting options regardless of whether the page is in a postback or not inside the Page_Load or OnInit handlers of the page. This will reconstruct voteOptions, which will then be accessed when Submit_Click is called.
Take a look at the ASP.NET Page Life Cycle.
The problem seems to be that you are constructing the List<VoteOption> voteOptions at page render then expecting it to still be there on postback. The Page object does not exist past the point that the page is delivered to the browser, so your list of vote options gets disposed of as well when the browser has received the page.
You'll either need to reconstruct the voteOption list before or during Submit_Click on postback, or give yourself enough information in the value of the radio button that you don't need it.
I don't see in your code any place where the list that you are building is placed in memory. I believe you are rebuilding it on each page reload. P.s. might be my reading but you created a function called registerVote and you are calling a method called registerMovie so that might be your problem.
You could place the list in the session and get it back from session.
Personnally I would change the code to
1) Check if the list is in memory and get it. If not in memory call a method to generate it once and then place it in memory.
2) Use a RadioButtonList on your page that you can then bind to your list as a data source.
asp.net is stateless, so every postback (such as clicking Submit) recreates the server-side class. If you want your list to persist between calls, you should save it in ViewState or a Hidden field. Not sure about the string though; what you're describing doesn't fit the asp.net lifecycle.