Visual Basic Web Form Close() Method Not Working - asp.net

Form Design
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
End Class
Form Design =screenshot of the Web Form I am trying to design
I am trying to get the close button to work. When I created an event procedure for the button to work, I assumed the Me.Close() method would work, but an error occurred and it doesn't seem to be recognized. Does anyone know how to actually get the web form / window to close when the close button is clicked?
Sorry about formatting, this is my first question asked on here.

Well, in desktop land, we can do this:
form1: click button - open form2
In form2, click on button, close form (that would be form2), and THEN we return to form1.
In web land, you don't have the above "approach" anymore.
In web land?
Form1: click button JUMP or "navagte" to form2.
At this point in time, we are now on web page and URL form2.
You can't close the web browser (as a general rule).
So, if you want to close the Form2, you navigate and jump BACK to Form1.
So, it will look like this:
So say on form 1 we have this:
<br />
<h2>Click on button to pick favorte food</h2>
<asp:Button ID="Button1" runat="server" Text="Jump to Form2 to pick food" />
<br />
<br />
<h2>Favorate food picked</h2>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
We get this:
So, lets wire up the button click
So, we double click on that button and in code behind we write this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Session("FavorateFood") Is Nothing Then
Label1.Text = Session("FavorateFood")
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Response.Redirect("WebForm2.aspx")
End Sub
So, we click on the button, and jump to Form2.
We have this on that page:
<h2>Please pick your favorate food</h2>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>Pork Chops</asp:ListItem>
<asp:ListItem>Cherry Pie</asp:ListItem>
<asp:ListItem>Lobster</asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="Button1" runat="server" Text="Done, return back to Form1" />
And we see this:
And the code behind for that button click is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Session("FavorateFood") = RadioButtonList1.SelectedItem.Text
Response.Redirect("WebForm1.aspx")
End Sub
So, we pick a food, but note how we DO NOT have the concept of closing the form, but only that of jumping back (navigating) to the first form.
So, I can pick a food, and click the button, we get this:
so, as a general rule ask this question:
In the past years, when you used a web site, did you EVER click a button, and it closed down your web browser? No, it never does and did. There are RARE cases when you might want to do that, but I can't think of in the last 10 years, that I ever clicked on a button, and it closed the web browser. In fact, users don't like it much when you try to close a web browser - and you often see a prompt that tells you the web site is trying to close your browser - and will you allow it???
so, in web land, the concept of
Open a form
close a form
it does not really exist - you can jump to new web page, but the idea of open and close does not really exist as a concept in web land, and thus your designs and how you approach software has to be changed. In other words, the long time desktop concept of open form, and close form has to be dropped from your design approach here.

Related

How do I prevent __DoPostBack refreshing an ASPX page?

I have a JS function in an ASPX page that performs a __doPostBack to a vb.net code behind. The problem is that it is forcing the page to refresh. How can I prevent this? My code below...
JS:
__doPostBack('', 'test');
VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Select Case Request.Form("__EVENTARGUMENT")
Case "test"
RadMediaPlayer1.Source = url
End Select
End Sub
Thanks!
There is one easy way, and then one hard way.
The first issue? asp.net web pages are in fact designed to near ALWAYS have and endure post-backs.
This quite much means that any button, any combo box, or just about anything on that page to run some code behind WILL cause a page post-back.
And thankfully due to automatic "view state" management, most controls, and even a grid view, or even a combo box selection will correctly maintain its values for you (its view state).
So, if you don't want the whole page to post back and refresh?
Then you can drop in a plane jane asp.net button, and say whatever it is you want to "only update", then try using what is called a update panel.
Try a quick test page like this:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
And our code behind like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = Date.Now
System.Threading.Thread.Sleep(700)
End Sub
Now, I put in a 3/4 of second delay - just to help you see the effects of this (you don't want that delay sleep() in your actual code.
Ok, now run the above page, click on the button. You see the traditional post-back, you see the browser "spinner"/wait occur, and then the text box is updated.
Now, lets use what is called a update panel - and I am going to suggest you try one.
You can even dump/drop the JavaScript you have now.
So, you have to drop into the page a script manager, and then move your content inside of he update panel. It will now look like this:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Give above a try - note how the page don't post-back any more? How cool is that!!!
So, add update panel, content template. And move your button, and the adMediaPlayer1 into that panel.
You don't even need to adopt any JavaScript here. Drop in a plane jane button, and just have normal code behind for that button. Say like this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RadMediaPlayer1.Source = "some real url goes here"
End Sub
A few things:
While this looks, feels and appears to NOT do a post back and the .net system will wire this up for you automatic - VERY much like a ajax call?
Don't put too much inside of those update panels.
and keep in mind, while this does not seem to do a post back? In fact this results in what we call a "partial" post back. The page load event even will fire.
Note that code behind CAN ONLY now modify controls inside of that update panel. Other controls on the page are off limits. (unless you move them into that update panel also).
But, dump your JavaScript button or code for the post back. Just move in the media control and your button to inside of that up date panel. Give this a try - you not see a post back - you not see the browser "spinner"/wait run at all.
This feature is great - but a not a cure all.
The next way to do this?
Is you can setup what is called a ajax call. This can call code behind, but keep in mind the code behind can't update controls on the page (due to no post-back). If you don't do a post-back, then code behind can't touch controls on the page.
This would suggest that you have a client side button - click on it, it runs JavaScript, calls some code behind, code behind returns a result, and then in JavaScript you stuff/change the URL of the given control. Since you changing that URL in pure JavaScript at this point? You probably don't even need to write or call code behind anyway.
but, try the update panel - they are very useful. But, keep in mind behind, the .net system is doing a bit of fakery to achieve this goal, and what a partial page post- back does occur.
Edit: pass value from js and click button
So, as noted, if you have a post back, you get page refresh!!! - that's what the command does and means!! So, you can't say I dont want to post back and not refresh the page, and then do a post back!!!
However, as noted, your js code is "obviously" a much larger example, and you sharing of JUST the __DoPostBack() in js is as you noted a larger set of code and routines here.
However, I still suggest you use a update panel.
You can keep 99% of your js code now, and just remove the _dopost back.
Move your case statement code to a button. (yes, a button click code stub).
What we THEN do is this:
The js code can figure out and do whatever it needs. Obviously we reach a point in which a VALUE of some type has to be passed to the server. And then what we will do is then use js code to CLICK the button - the ONE inside of the update panel. This will and should prevent a page refresh. And we pass the value by using a asp.net hidden field control (you could even use a hidden text box - but it don't matter - hidden field is probably better).
So, the pattern, and code will look like this:
We drop a button, hidden field, and that other video or whatever control is is the page - all inside the update panel.
then your js code? It runs, gets the final value. We shove that value into a hidden field control, and then use js to click the button - also inside of that panel.
Thus, you move your on load code + case statement to the button click code.
Like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' get value passed from js
Dim strMyValue As String = Me.HiddenField1.Value
Debug.Print(strMyValue)
Select Case strMyValue
Case "test"
Case "zoo"
Case "my fun test"
End Select
End Sub
And the markup is this:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" ClientIDMode="Static" />
<br />
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="js post back"
OnClientClick="mypost();return false;"
/>
<script>
function mypost() {
// set value to pass to button click
$('#HiddenField1').val("my fun test")
$('#Button1').click()
}
</script>
</div>
So, in place of your doPostback, you set the hidden field, and then with js click the button. (once you get this workng, then hide the button with style="display:none"
Of course, you proably have a bunch of postback in your code.
So, make a js function called MyPostBack, say like this:
function MyPostBack(sValue) {
// set value to pass to button click
$('#HiddenField1').val(sValue)
$('#Button1').click()
}
Now, you can replace all your _DoPostBack('', 'test')
With MyPostBack('test')
So, in the update panel, put the hidden field, the button, and that other control. And your js code will now "click" that button in the panel.
Note that the js code above does assume you using jQuery. However, you can code in pure js, and not necessary use jQuery short hand as I did above.

Asp button does not fire OnClick event

I've searched the forums and have yet to find a soln to my specific problem. I'm writing an asp.net aspx page with
<asp:Button ID="Add" OnClick="Add_Click" runat="server" Text="Add" CausesValidation="False"/>
where Visual Studio even autofilled my OnClick function, and my VB code behind function looks like this:
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Server.Transfer("TimeReportingAdd.aspx", False)
End Sub
I have another page with a button set similarly and it works fine. Does not even hit event during a debug. The main page (TimeReporting.aspx) just refreshes on the click and I would like it to redirect to another page (TimeReportingAdd.aspx). The button was not copied but created new and the event was created by double clicking in the designer. runat="server" is present in all my content headers etc. I don't think my TimeReporting.aspx page header needs any validation elements because the page that works doesn't have them. The Add button is declared as follows in my vb code behind:
Protected WithEvents Add As Global.System.Web.UI.WebControls.Button
Also, the button that works in another page is easier, doesnt even have onclick or validation:
<asp:Button ID="Button1" runat="server" Text="Query" />
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
...
End Sub
I've tried deleting the button and adding it again multiple times. Thanks in advance!
Please remove OnClick="Add_Click". This will fix your problem.
There are two things you need to consider:-
When you add OnClick, this means you want to handle click in Java Script.
To handle click in server side, you provide a method in code behind with Handles clause.
First approach overrides second one.
I was able to get this to work by giving this property in my button:
PostBackUrl="~/TimeReportingAdd.aspx"
It was posting back to the initial page TimeReporting.aspx

Retain selectedvalue of dropdownlist after postback

I've found this question asked countless times, but the answers haven't worked for me:
I have an asp:Dropdownlist that is dynamically bound from an asp:Objectdatasource. A button calls a codebehind function to store the selected value. However, in the click event function the value of the dropdown is always reset to default, AFAIK due to a postback that is called before the click event handler. When debugging I've checked that ViewStateMode is enabled and EnableViewState is true. I've been stuck with this for hours now, does anyone have a clue?
ASPX markup:
<asp:DropDownList runat="server" DataSourceID="AvailableNivamalerODS" ID="AddNivamalerDDL" />
<asp:ObjectDataSource runat="server" ID="AvailableNivamalerODS" TypeName="Nivamaler.NivamalerPresenter"
SelectMethod="GetAvailableNivamalers"></asp:ObjectDataSource>
<asp:Button runat="server"
Text="Legg til"
OnClick="AddNivamalerToTjstpl"
ID="AddNivamalerBtn"
UseSubmitBehavior="False"
CssClass="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"/>
Codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
AddNivamalerDDL.DataBind()
End If
End Sub
Click event handler:
Protected Sub AddNivamalerToTjstpl(sender As Object, e As EventArgs) Handles AddNivamalerBtn.Click
Dim nivamalerId As Integer = AddNivamalerDDL.SelectedValue
'Here nivamalerId is always the default value
End Sub
Cheers!
EDIT
The replies to previous question have basically said to put the data binding in the Page_Init method or the Page_Load method after !IsPostBack, which didn't help me.
Also a disclaimer: This is a legacy project with tons more code (the relevant code is new), but I tried to snip out the relevant bits. As far as I can see the rest of the code shouldn't affect this, but I can't be certain as I am still fairly new to ASP.Net
Put your page_load code into the page_Init section. The asp lifecycle will make the dropdown list databind() be absolutely meaningless if it is in the page load section here because a Postback causes the whole page to resubmit itself to the point of page_load and since you have the if not ispostback statement, it will reload the page structure but won't run your page load code and that is where you are losing your value. Other than that the code is fine.
I solved it, and as has been pointed out, the posted code is incomplete: The dropdown is inside a JQuery-ui dialog, which makes the dropdown lose its state. I ended up with a workaround with a Javascript function which copied the selected value to a hidden field outside the dialog and using the hidden field value in the codebehind

ImageButton event not firing on only one page

I have a problem on one page in my entire solution where it seems the on click event for the image button is not firing.Firstly let me describe the relevant parts of the website.
There is a total of four pages involved in this problem.Pages A-D.
I start on Page A from which I navigate to Page B via an ImageButton which works.Here some data is captured and I navigate further to Page C via another ImageButton which works.On Page C I have two ImageButtons,these are the ones giving me trouble.One is simply supposed to take me back to Page A and the other takes me to Page D.The one that takes me to Page D I send some arguments along.
Now if I click on either of these I get taken back to Page A,however when debugging even on the one thats supposed to take me back I cant see the code being hit.Here is how I have my buttons defined in the aspx page:
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/backBtn.jpg" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/nextBtn.png" />
And my code behind for them is as follows:
Protected Sub ImageButton1_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Response.Redirect("pageA.aspx")
End Sub
Protected Sub ImageButton2_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs) Handles ImageButton2.Click
Response.Redirect("pageD.aspx?option=4&ref=" & lblInfo.Text)
End Sub
The buttons aren't in a update panel.Things I have tried to do to fix this :
Remove them and readd them from scratch.
Turn into normal asp:Button to see if its a problem with ImageButtons,problem was still there.
Set AutoEventWireUp to true.
Explicitly set OnClick in aspx to the method.
Set CausesValidation to false.
None of the above has worked.If anyone can help I would be very gratefull.
No url rewriting or default document involved ?
Could it be some code in pageC or some base class, which triggers on postback before click-events handling, and redirects to page A ?
(maybe some error handling which redirects to pageA)

Dynamic creation of ASP.NET Form Elements

I'm trying to build a form which generates itself as it is used. I have created a really simplistic example, loosely related to what I'm trying to do below, but which demonstrates the problem.
The user types a word in the text box, clicks the Button and a new TextBox is loaded into a Panel, with the value in the original TextBox that the user has entered. The user should then be able to type something else/the same and create another text box with that in it by clicking the button, basically permitting 0,1,..,n textboxes appearing above the "txtFeeder" TextBox on the form.
The problem is that everytime you click the button, it doesn't add a new control, it seems to just update the one that has already been created with the new (incremental) ID. I'm not sure if I'm doing something wrong, or if what I'm trying to do can't be done (which I find hard to believe)?
Here's the .aspx...
<form id="frmMain" runat="server">
<asp:Panel ID="pnlAdded" runat="server"></asp:Panel>
<asp:TextBox ID="txtFeeder" runat="server"></asp:TextBox>
<asp:Button ID="btnFeedPanel" runat="server" Text="Button" />
</form>
...and here's the .aspx.vb...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ViewState.Add("elementCount", 0)
End If
End Sub
Protected Sub btnFeedPanel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFeedPanel.Click
ViewState("elementCount") += 1
Dim txtNew = New TextBox
txtNew.ID = "txtElement" & ViewState("elementCount")
txtNew.Text = txtFeeder.Text
pnlAdded.Controls.Add(txtNew)
txtNew = Nothing
End Sub
Thanks
On PostBack you need to explicitly regenerate the buttons from ViewState (you check the added counter you have in the viewstate and regenerate the added buttons) - otherwise they'll be gone (and only the original one will appear, as you're experiencing).
Have a look at this question, the guy is trying to achieve smt extremely similar to what you're looking for (maintaining a bunch of dynamic buttons and regenerating them on postback).
Controls that are added to a page dynamically are not automatically retained between form posts. The control itself isn't preserved in the page's view state. I think you'll need to rebuild all of the previously added fields every time a postback occurs.

Resources