I have a situation where I need to ignore parts of page load sub inside a isPostback = true. Basically inside the isPostBack I want something like if button1 caused postback.... do this else do this...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = True Then
If TextBox1.Text <> String.Empty Then
CheckDate()
End If
End If
End Sub
I think what you need is the reference to the control name which triggered the postback.
http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
Implement the solution which is there in the above link (Got it from here.... How to Get Source of postback)
If the control name is your button then do not do what needs to be done upon postback.
HTH
You should probably not have all this going on inside the Page_Load event. Instead, you should be handling events for each control that can cause a postback. This helps with code clarity, and ease of maintenance, not to mention better control in the first place.
Here's a nice brief blog entry I found on the subject: http://www.sitepoint.com/blogs/2007/01/21/page_load-is-evil/
Incidentally, handling events is much different in ASP.NET than in other environments, My guess, just based on the fact that you're trying to accomplish this in the Page_Load event is that you're not yet "getting" the event-driven programming model. (If I'm wrong, I apologize, I don't mean to be insulting).
If I'm right, however, once you get used to it, it's going to be a lot simpler for you than things were in the classic ASP days, for example, where you had to do things like try to figure out which button was clicked. Here's another nice article to explain this further: http://articles.sitepoint.com/article/driven-asp-net-development-c
It's hard to see this as a good idea. From the short snippet you posted, it looks like what you really need is a Validation control attached to your textbox.
Have a look at the POSTed items. You should see some sort of reference to that button in there. IIRC, if it was clicked, you will see some sort of reference in there, and if it wasn't it wouldn't be in there.
I had this same problem a while a ago and that's how I circumvented loading some stuff.
Related
I recently encountered a bug in my workplace where Server.Transferring to the page that's already active triggers a StackOverflow if the preserveForm param is True.
Example button that would trigger an overflow:
Private Sub bugTest_Click(sender As Object, e As EventArgs) Handles bugTest.Click
Server.Transfer("current aspx page", True)
End Sub
I know that the problem can be avoided by setting preserveForm to false or using Response.Redirect instead, but I was hoping to get a better understanding of why the bug happens in the first place.
I do have some theories about what might cause it but I don't feel confident enough in any of them to actually explain the cause to my coworkers, and my boss would really like to understand why the bug happens.
I have a simple timer method in vb, that currently does nothing, it just ticks. Once it does however, all my other code on the page stops working.
as an example, I have image buttons on my page that add controls to a static place holder.
btnCreate.Text = "Create"
btnCreate.ID = "btnCreateSpecialNotes"
AddHandler btnCreate.Click, AddressOf btnCreateSpecialNotes_Click
plhCreateSpecialNotes.Controls.Add(btnCreate)
so without the timer.tick method, that (along with other code not included) would fire off as expected and do what I want, but when the timer.tick happens, everything sort of freezes and nothing works.
My timer is set up as follows
<asp:Timer ID="specialNotesTimer" runat="server" Interval="2000" ontick="specialNotesTimer_Tick"></asp: Timer>
and in the code behind...
Protected Sub specialNotesTimer_Tick(Byval sender as object, Byval e as eventArgs) Handles specialNotesTimer.Tick
'Do things to the page
End Sub
DISCLAIMER: I have never used the System.Web.UI.Timer class.
I think there might be some confusion between client side javascript code and server side C# code.
After reading MSDN, it seems that the Timer control would initiate a full postback every 2000 milliseconds (2 seconds because you say so above). This can only be done in javascript and there needs to be a server side event handler that will perform some task on the server (you call it specialNotesTimer_Tick).
Now, if this task takes longer than 2 seconds to execute, I would assume that you will never see any information on the web page because it would constantly be postbacking (posting back?) and refreshing the screen.
Suggestions:
Reconsider your approach for using a timer
Increase the timer interval
Add an UpdatePanel so the processing happens asynchronously, thus avoiding the screen refresh
Hope this helps.
I think the main problem I had here was the flow of my html wasn't ending. I restarted my page from scratch slowly, and though I used virtually the identical code, I just triple checked all my close tags and what not in html, and that seemed to solve the problem itself.
I'm sorry there isn't a more in depth answer, but I still don't understand why my old code here wasn't working, but re-doing my page from square one worked for me.
Is it a "Best Practice" to always use .IsPostBack in the Page_Load sub routine of a web form like in this example coding?
I hope it's ok to ask this question. If not, I will immediately remove the question.
Basically I want to code the way most of you are coding.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
' More coding will go here.
'--------------------------
End If
Please give pros and cons for it's usage.
It's not so much a case of "Best Practice" but more a case of whether you need to use it at all.
It's true, you would normally put IsPostBack in the Page_Load, though you could also put it in the Page_Init - basically in any of the page events that fire before rendering out the HTML.
You're essentially using the command to, in this case, prevent the code in the body from firing when the page posts back to itself; such as a form submission or AutoPostBack on a server control, for example the DropDownList.
There aren't any, at least that I can think of, pro's and con's. Its a case of need or don't.
An example of when you would ideally need it would be only wanting to get data from the database once and bind it to a DropDownList. This data would be available in the viewstate when you postback. so you wouldn't need to visit the database again on postback.
An example of when you wouldn't put code in it is if you were generating server controls (button for example) that have an event handler, such as click, added at the same time. this would need to be re-generated on postback for the event handler to be available.
The benefit is that you can do your expensive operations only once. Binding to gridView...etc.
Mostly stuff you do not want to perform during a refresh.
It always depends on what you want to optimize. If your initialization code takes a long time, it is better to do it only the first time and let your controls be initialize through ViewState. Then you use If Not IsPostBack.
But if you target for mobile devices where bandwidth is more important, you might turn of the ViewState and initialize your data again on postbacks (you could read it from Cache or from SessionState). Always watch your ViewState, I have seen pages with 20 kByte ViewState or more.
Pros:
less overhead for initialization (e.g. access to database)
less memory on server (session or cache)
Contra:
more bandwith for ViewState
I researched this problem here on SO and tried the apparent solution which did not work, so here it is:
I have a very complex form with among other controls, three autocompleting textboxes.
I also have a client who cannot seem to stop entering a value in the textboxes and hitting the Enter key to select the desired value from the autocomplete list.
When they hit Enter, the first imagebutton in the form fires, doing something completely different. So to them, the form is broken.
What I need to do is to prevent the Enter key from firing these imagebuttons (there are 10 of them in the form).
I have tried the following code in both Page_Load and Page_LoadComplete, neither of which work:
imgbtn1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")
Any advice that saves me a few hairs is appreciated.
One good solution can be found here:
Disable Button click, ImageButton click and/or form submit on Enter Keypress
Adding Markup from Link
<form id="form1" runat="server">
<input type="submit" style="position:absolute;left:-100px;top:-100px;width:0px;height:0px;" onclick="javascript:return false;" />
<!-- other form controls below this line -->
</form>
Did you check these two references
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
http://www.webcheatsheet.com/javascript/disable_enter_key.php
They are essentially doing the same thing you are trying, just that they are hooking it up to a different event. Also make sure that your Javascript is foolproof i.e. if javascript has some errors, then your end result may not be as expected.
The second link Subhash Dike posted (Disable Enter Key) worked for me. I have two ImageButtons and they both don't fire a postback when using this function (bit modified from the original) which is great.
document.onkeypress = function (evt) {
return ((evt) ? evt : ((event) ? event : null)).keyCode != 13;
};
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Form.DefaultButton = BtSearch.UniqueID
If Not IsPostBack Then
' ...............
End If
End Sub
I had a similar problem.
Listview1.ImageButton was responding to ENTER.
We really want a SAVE to happen (or nothing, but the bad behaviour was reloading the page and that made them grumpy)
Set up a handler for the window to catch events. I do this in docReady()
function docReady() {
$(document).keydown(mapKeyCode);
};
In that handler, find the keycode you want to capture ( enter is 13)
https://css-tricks.com/snippets/javascript/javascript-keycodes/
function mapKeyCode(event) {
{
if (event.keyCode == 13) {
//event.stopPropagation();
//event.preventDefault();
__doPostBack('ctl00$cp1$InventoryPieces$btnSubmit', '');
}
}
event.StopPropogation will cause nothing to happen.The keystroke is simply eaten. That may be what you want. You are still free to call an ajax method below, that's not part of the event.
event.PreventDefault is supposed to stop the event from doing what it normally does. I had troubles seeing a difference w/ this line commented out or not. There is in depth discussion on preventDefault and ENTER here on SO.
This 3rd line is what the people who pay me want to have happen when they hit the ENTER key even though they probably should be hitting tab. I tried (#).trigger() and didn't have a lot of luck. Inspecting the element, I saw that it was calling __postback, so I pasted that in. I'm reasonably certain ().Trigger would work if i figured out what i was doing wrong, I just took another route.
This is hackish to me, but it accomplishes the objective.
Hope it helps.
How can I modify the head portion of a page from within an embeded user control? I know I can have the control run in the head portion of the .aspx page but I have a existing site with numerous pages that I don't want to change. One thing they all have in common is the menubar.ascx. So, I figured I could put the code there to modify the head element of the containing page, but no dice. The code I am trying to implement looks like this, however, the Page.Header is null.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim favicon As New HtmlLink
favicon.Attributes.Add("REL", "SHORTCUT ICON")
favicon.Attributes.Add("HREF", "images/bh_favicon.ico")
Page.Header.Controls.Add(favicon)
End Sub
I tried putting it in the PreRender and the Render events but same thing. The Page.Parent.Page.Header is null too. Is there a better way to do what I want to do? Utlimately I want to add a favicon to a group of pages that is different from the default favicon. Basically I have two sites on in the same code base.
Be nice, this is my first post.
TIA
You may need to make your Page Head run at server, so the usercontrol can see it.
eg:
<head runat="server">
Which I guess sort of defeats the point if this isn't already done on all your pages. Maybe a solution wide RegEx search/replace would be in order to implement this.
Thanks for your answers. I know I was asking for the least amount of work solution, however, I want to make the code easy for me to manage. I think what I am going to do is construct a master page as a template for all pages (like #devstuff suggested). Then I am going to change the existing pages, about 50 pages, to use the master page. That way if something like this pops in the future I can easily change everything in one place.
Thanks for you help!
As mentioned by #Program.X you may need a full search/replace. If you are going to do that you might want to go one step further and use a Master page, but it really depends on your time constraints and how many pages there are to modify.