ASP.NET - Refreshing GridView Data on Page After Button Click - asp.net

I've been working with C# and .NET for quite some time now, but am currently working on my first ever web application with ASP.NET. It took me quite some time playing around to realize that the Page_Load function was getting called before my button event handler, though, at this point I've got the application working properly around this behavior. However, the issue I'm having is this:
I have a GridView control that is bound to a SortedList in my application. The button click event handler saves data in a form to the database (actually, saves data via a SOAP service), then updates the list that the GridView is bound to in order to reflect the most up-to-date data (again, updates the list from the SOAP service). However, because the page refreshes before my button click event handler fires, the data doesn't actually appear updated on the page. What is the proper way to handle a situation like this? How can I get the data on the page to be refreshed, or at least up-to-date, after the button handler saves data even though the page has already refreshed? I've been struggling with this for quite awhile now, so any code example or links that'll help explain this would be much appreciated.
Thanks in advance!

try inside Page_Load
if (!IsPostBack)
{
//Bind your Grid
}

just write your code in below if condition.
if(!IsPostBack)
{
write your code here in formload.
}

I want to correct Harag's link to the resource regarding the page lifecycle. It can be found here: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx.
Though not an answer to the OP's question, I restate it because it's such an important concept to know once you start programming web forms on a more serious basis.

Related

Force the ASP.NET page lifecycle to go forward

Ok, so I am working on a custom framework above the .NET framework, and some instructions are not written / called at the good places.
For example, a postback is done on the same page. Then, a Response.redirect occurs right within the page_load; but at this point, the new values of the controls of the page are not yet handled, so they get lost...
Therefore, I wanted to know whether it was possible to force the pagelife_cycle to go forward before the call to response.redirect, so that I can get the right values.
I can't just make that call in another function, because the page I am working on is called by many web applications (about 1-2k), and it would completely change their behaviour, which is not acceptable!
Is that even possible?
See a bit the second image and the Load PostBack Data section. Before the Load event of the page is raised, a textbox is already initialized. You can catch the value by overriding OnPreLoad or by adding a handler at PreLoad event.

Problem with asp.net C# focus, page_load

I'm really new to asp.net and have a couple of issues I'm trying to get fixed. I have some programming experience, but it is not asp.net. However, I've been able to follow the code enough to make other changes in the code to fix other issues.
The first is this:
I'm working with a form that has a calculate amount method that gets called when the user inputs a value in an amount text box. The same method gets called when the next control, number of payments, has a value.
So in the two controls:
onTextChanged="ctrlName_textChanged"
Then in the code behind, the textchanged method does:
calculateAmount();
The problem is after the amount is calculated and returns, the focus seems to get reset and the user has to tab all the way back through the form to the place they were.
The textboxes in question are in a panel that starts out hidden and is made visible conditionally.
My apologies if I have not used the proper .net terminology.
It looks like the same issue may be causing my second problem. When the user types in an amount and then tabs and quickly adds the number of payments, you can see the amount get calculated correctly and very shortly displays the proper total in the total amount text box. However, even though it shows for that short time, the tab order again gets reset as well as the total amount value.
I've looked at different methods to try and fix the focus issue.
In the textchanged method, I tried using something like:
Session["myval"] = "someval";
Then tried to check against that in Page_Load with something like:
if(Session["myval"] != null) {
this.NextControl_Name.Focus();
}
but it didn't ever work correctly.
I also tried to set a cookie in that same textchanged method using something like this:
Response.Cookies["myval"].Value = "somevalue";
Then tried to check that in Page_Load using something like the previous if block above but using Request.Cookies["myval"] as the source.
Is there a good reference with some really clear code samples I can look at for this type of implementation?
Thank you in advance,
C.
Sounds like you have a postback problem...
Remember that the web is stateless. This means that when you have a web page rendered out in .NET and you attach an event that executes serverside code... it does an HTTP POST back to the server which is effectively a new page request. The Page_Load method will fire again as well as your bound event. So your onTextChanged event is firing a new request back to the server. This is why you see the focus reset and why when you tab quickly, the value seems to disappear magically.
You can do one of several things, you can implement the UpdatePanel in the AjaxControlToolkit
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/
you can use PageMethods and do your validation with javascript and jQuery (or other js library)
see page method info http://www.geekzilla.co.uk/View30F417D1-8E5B-4C03-99EB-379F167F26B6.htm
Hope this helps

What are the main differences of defining a control statically or creating it dynamically on page load?

I am working on a project which creates controls dynamically for a form in the page_load event, loads in their current values from the database and saves their values (using FindControl) when the user clicks the continue button.
When I added a control statically in the .aspx page and followed their same procedure of loading the value in the page load and saving it on the button press I found that the value would not save correctly. It seems that it wouldn't save because the click event fires after the page_load, so the page_load of the post back reverted the value and the user entered value was not saved.
The strange thing is that by changing the control to be dynamically created just as all the other controls on the page and keeping the loading and saving the same it now works. Even though the page load still creates the control with the old database value.
It seems like a very fundamental asp .net feature here but i'm just unclear as to what is going on. I suspect it is to do with the timing of creation and maybe when the view state kicks in.
Static page controls are created just like dynamic page controls. The difference might be coming in your Page_Load. Whenever you postback all the controls are created afresh which means they are created with their initial values. This happens because after creating the controls asp.net throws away the controls/objects.
So, when the request comes, the first thing that asp.net does it to recreate the controls by looking at their definitions (in the designer files). On each postback they are created and initialized again losing their state in the process.
But after creating the controls Asp.Net loads any viewstate that is sent along with the request which makes people think that the state is always saved at the server.
What might be happening is that either the viewstate is not enabled for your control (in case they are created in designer), in which case you may try using EnableViewState property to true of the control.
Or, when you're doing a Page_Load, you're forcefully re-initializing everything. And in process losing all the control data. If you could post the logic of Page_Load, it might get clarified.
Make sure that:
you are not setting the value again for the static control in Page_Load. The dynamic control are probably getting around it by grabbing the ViewState and form values at a different stage in the lifecycle.
The dynamic controls are added After the static control. Or at least they are added in a different container. Placement in the control's collection can affect the ViewState, although it doesn't look like your scenario / since what you mention seems to be more about the values in the current post.
The save is happening After the Page_Load in response to the corresponding event.
I've run into similar problems in the past (quite a few times actually), but what helped me the most is understanding the ASP.NET Page Lifecycle.
Microsoft has an article on it which describes it pretty well, but this post by Solomon Shaffer really cleared up everything.
I suggest reading them both and coming back with additional questions regarding to a particular state, when to load/save data etc..
Hope this helps.
Marko
Note that you may want to use Page.IsPostBack property to avoid reinitializing values on button clicks and other events.
private void Page_Load()
{
if (!this.IsPostBack)
{
// Assign values to the controls.
}
}

triggering javascript events using asp.net

I'm writing an asp.net web app. and i've hit a bit of a brick wall.
basically i have 2 pages, the main page with a text box in and a popup that contains a treeview.
My problem is this. when i select a treeview item i want the program to perform some database transactions using asp.net and then pass the value retrieved from the database into a javascript function that passes the data back from the popup page to the parent page. My problem is that i cannot find any way of calling a javascript function from asp.net. I've tried assigning attributes to controls on page load, but this does not work as when the page loads the data has not been retrieved from the database.
Have a look at the ClientScriptManager class. You can register scripts from code-behind that will run when the HTML page loads. Those scripts can call other javascript functions on the page.
There are many tutorials and examples on the Web. Here's one I found that may help but there are many more.
How to use the client script manager
You hit the nail on the head when you said "I've tried assigning attributes to controls on page load, but this does not work as when the page loads the data has not been retrieved from the database." You just need to discover when you're pulling the data from the database, and then assign the values after that. Without looking at your code, there's no way to know for sure, but Page_PreRender is probably a good bet to assign your values...it's probably after you're pulling information from the db...it's pretty much the last place that you can make things happen before the html is generated for the client.
You can invoke a function resided in the Main Page and call that function in the Main Page from the Child Page which is your pop up window.
Please refer to these links for references
http://chiragrdarji.wordpress.com/2007/03/10/call-parent-windows-javascript-function-from-child-window-or-passing-data-from-child-window-to-parent-window-in-javascript/
http://www.webmasterworld.com/forum91/2957.htm
http://hspinfo.wordpress.com/2008/01/12/call-parent-windows-javascript-function-from-child-window/
This one helps with retrieving popups from values using javascript
http://www.eggheadcafe.com/articles/20060117.asp
This one shows how to fire a postback using javascript, and manage it in the codebehind.
http://weblogs.asp.net/mnolton/archive/2003/06/04/8260.aspx
If you put them together, and use Control.ClientID to find the actual "html name" of your asp.net controls, you'll be able to set that up in no time.
Might not be the prettiest way to do it in town, and incidentally make little baby Jesus cry, but anyway, it works.
[edit]Oh. I just saw that it seems I answered the question the other way around, or "how to trigger codebehind from Javascript". I think the method I suggest may help you, if you use it right.
The javascript of the popup should pass the information to the parent window, and the parent window function should call a postback when it receives the information.
The javascript of the popup window should be only registered on a postback with the correct information retrieved, so that when the postback occurs on the popup because of the selection of the right information, the window closes and passes the information to the parent page.
The parent page, triggering postback, does the thingies you need it to, and the app resumes "normally" from there on, doing whatever you need it to, outside of the popup page.

ASP.NET: How to initialize when *user control* is initially loaded

I have an ASP.NET user control that I'm embedding in another user control. This works fine.
I need to know the best logic/method for detecting when the control is loaded. In other words, I have some display initialization logic that needs to run when the control is initially displayed. Surely there is a pattern for this.
The typical method is to put (!IsPostBack) logic in the Page_Load method of the control. This works great until you end up with a state when the Parent page has already posted back many times. My user control gets added to the page but its display does not intialize properly.
I'm hoping to find a way that keeps this logic inside the control, versus various hacking around in the codebehind of the parent page.
See the following MS article. They have an example that places several controls within a user control and initializes them.
There is another post here on StackOverflow that seems similar. You may want to check it out, and see if it points you in the right direction.
It may also be helpful to review the page life-cycle and events.

Resources