Solved

WHy doesn't my window.close work in VB.Net?

Posted on 2009-05-14
32
1,275 Views
Last Modified: 2012-06-27
The script below grabs an email username from a LinkButton and redirects to another page with a form that does stuff with that username.  Then I want this window to close.  I've declared my JavaScript as a string and call it with Response.Write, but the window doesn't close.  The redirecting works fine, but the window closing doesn't happen at all.  What am I missing?
<script runat="server" language="vb">

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

	Dim closeWindowScript As String

	closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"

	Response.Write(closeWindowScript)

End Sub

</script>

Open in new window

0
Comment
Question by:mrcoulson
  • 15
  • 11
  • 6
32 Comments
 
LVL 10

Expert Comment

by:cdebel
ID: 24389048
How do you call this script?  Which event?

You also forgot to use the PageRegisterScript or something like that
0
 

Author Comment

by:mrcoulson
ID: 24389087
Forgetting would presuppose that I knew about it to begin with ;)

See below for simplified code that only has the form tag and the LinkButton.
<form id="supervisorForm" runat="server" target="_new">

<asp:LinkButton ID="LinkButton1" runat="server" Text="Email Gary" CommandArgument="gary@garylofton.org" CommandName="SetSessionVariable" OnCommand="SetSessionVariable" />

</form>

Open in new window

0
 

Author Comment

by:mrcoulson
ID: 24389098
Or the whole stinkin' page if it helps!
<%@ Page Language="VB" %>

<%@ Import Namespace="System" %>

<%@ Import Namespace="System.Collections.Generic" %>

<%@ Import Namespace="System.Linq" %>

<%@ Import Namespace="System.Web" %>

<%@ Import Namespace="System.Web.UI" %>

<%@ Import Namespace="System.Web.UI.WebControls" %>
 

<script runat="server" language="vb">

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

	Dim closeWindowScript As String

	closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"

	Response.Write(closeWindowScript)

End Sub

</script>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
 

<head runat="server">

<title>Back Creek Supervisor</title>

<link rel="shortcut icon" href="/FAVICON.ICO" type="image/x-icon" />

<style>

body {background-color: #ffffff;}

h2 {font-family: sans-serif;}

p {margin-right: 5%;}

.image {float: left; padding: 10px;}

.style1 {font-size: 18px}

</style>

<script type="text/javascript" src="/js/offsiteAlerter.js"></script>

</head>

<body>

<form id="supervisorForm" runat="server" target="_new">

<h2>Back Creek  Magisterial District</h2>

<div class="image"><img src="images/lofton.gif" /></div>

<p><span class="style171 style1"><strong>Gary A. Lofton</strong></span><br>

711 Buffalo Marsh Road<br />Middletown, VA 22645

<br>

(540) 869-1972<br />fax (540) 869-1972<br />

<asp:LinkButton ID="LinkButton1" runat="server" Text="Email Gary" CommandArgument="gary@garylofton.org" CommandName="SetSessionVariable" OnCommand="SetSessionVariable" /><br>

<br>

<span class="blurb">Gary Lofton was elected to the Board on January 1, 2008. </span></p>

<p><span class="blurb">Mr. Lofton represents the Board as a member of the Human Resources Committee Chairman; Code &amp; Ordinance Committee; Social Services Board;  Planning Commission liaison; Agricultural District Advisory; and Extension Leadership Council.</span></p>

<p><span class="blurb">Prior to his election to the Board, Mr. Lofton worked with VDOT for seven years and worked for the City of Winchester for 36+ years as Public Works Director and Director of Transportation. Mr. Lofton retired in 2006 and works as the Area Director for BNI-Shenandoah Valley.</span></p>

<p><span class="blurb">He is a graduate of James Wood High School and attended Lord Fairfax Community College. </span></p>

<center><p><input type=button value="Close Window" onClick="javascript:window.close();"></p></center>

</div>

</form>

</body>

</html>

Open in new window

0
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24389147
  1. You cannot close a window that was not opened by window.open (in some browsers like Firefox).
  2. Which page do you want to close? The current page or email_form_2.aspx? Response.write might not work after redirect.
Try this

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

        dim url as string"/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString())

Server.Execute(url)

        Dim closeWindowScript As String

        closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"

        Response.Write(closeWindowScript)

End Sub

Open in new window

0
 
LVL 10

Expert Comment

by:cdebel
ID: 24389158
Its ok.  Its normal that we don't know everything.  
First, i'm not even sure that your closeWindowScript get written because of the redirect.
Second, when you set a javascript to run on an html element, often you have to call the Page.RegisterStartupScript (my bad in my last comment).

There,s many ways to close a window...

in your example, you might want to add in your aspx file:  OnClientClick="window.close();"
0
 
LVL 10

Expert Comment

by:cdebel
ID: 24389246
Here's a method that i use sometime to close a window...

Let's say that i have a popup named "ScheduleEvent.aspx".
You need to name your body like this:
<body id="BodyTag" runat="server>

Then when you are ready to close your window (in your SetSessionVariable), you just call the CloseWindow function.

How it work?  easy... on call of CloseWindow, the page redirect to itself.  So the PreInit is called and since it see that you have set action=close, it assign some javascript code to the onload event of the body.  Then... just after the preinit, the body load and close the form.  This way you don't need any RegisterStartupScript.
--- this in your "Code Behind" ---

    Private Sub CloseWindow()

        Response.Redirect("ScheduleEvent.aspx?action=close")

    End Sub
 

    Private Sub ScheduleEvent_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

        If Request.QueryString.Get("action") = "close" Then

            BodyTag.Attributes.Add("onload", "javascript:(window.close())")

        End If

    End Sub

Open in new window

0
 

Author Comment

by:mrcoulson
ID: 24389317
Okay, taking these in turn.

baiju_nagori: Your idea gave me an error about the codebehind on the subsequent page.

cdebel: Your first idea: the window closed perfectly -- but before the redirect had a chance to happen.  I'll have to try your second idea later this evening.  I have to go home and tag-team my wife for watching the kids while she goes to work.

Jeremy


0
 
LVL 10

Expert Comment

by:cdebel
ID: 24389436
MrCoulson:  No problem.  I'm sure you won't have too much problem.  But may i ask why you do not just use:   Session("MyVariable") = e.CommandArgument.ToString()?

Is this line intended to close the aspx page that you have just shown us?
closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"

If so, then i don't understand why you close a window just after redirecting to another page.  The user will never get to see the page email_form_2.aspx.
0
 

Author Comment

by:mrcoulson
ID: 24395124
Okay, I'm still struggling here.  I've adapted your idea.  If the CommandArgument is not empty, then perform the redirect and run a closing script.  I don't think I can use "BodyTag.Attributes.Add("onload", "javascript:(window.close())")" because this window is already loaded.  Correct?

This window is a pop-up window.  When a user clicks the email link, I want the pop-up window to close and the email form to open in a new window.  Actually, I'd really prefer it to open in the window that launched the pop-up, but I believe I remember learning that it can't be done.

Also, I used to have this running with a session, but the email form is not in the same application as all the other pages.
<script runat="server" language="vb">

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	If e.CommandArgument.ToString() <> String.Empty Then

		Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

		Dim closeWindowScript As String

        closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"

        Response.Write(closeWindowScript)

	End If

End Sub

</script>

Open in new window

0
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24395187
Hi,

Why dont you use closeWindowScript in page load of email_form_2.aspx? On this page, you can just redirect.

Baiju
0
 

Author Comment

by:mrcoulson
ID: 24395276
Can email_form_2.aspx close popBackCreek.aspx?

The pages in real life: http://www.co.frederick.va.us/board_of_supervisors/.  Click on the guy who's second from left in that photo.
0
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24395470
Hi mrcoulson,

Add a literal control to popBackCreek.aspx and write closeWindowScript to the text property of that literal.

example

lit.text = "<script type='text/javascript'> { window.close(); }<" & "/script>"

Do this in SetSessionVariable
0
 

Author Comment

by:mrcoulson
ID: 24395857
Do I need to add the control first?

What is below also does not work.
<script runat="server" language="vb">

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

	Me.Controls.Add(New LiteralControl("<script type='text/javascript'> { window.close(); }<" & "/script>"))

End Sub

</script>

Open in new window

0
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24395887
Just add a literal control to your ASPX file.
<asp:Literal runat="server" id="lit"></asp:Literal>

and then use it

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
       lit.Text = "<script type='text/javascript'> { window.close(); }<" & "/script>"
End Sub
0
 

Author Comment

by:mrcoulson
ID: 24395895
Ah.  Trying now...
0
 

Author Comment

by:mrcoulson
ID: 24395916
No joy here.


' Function
 

<script runat="server" language="vb">

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

	lit.text = "<script type='text/javascript'> { window.close(); }<" & "/script>"

End Sub

</script>
 

' Control in ASPX
 

<asp:Literal runat="server" id="lit"></asp:Literal>

Open in new window

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:mrcoulson
ID: 24396075
Don't we need an event to trigger the script?
0
 
LVL 10

Expert Comment

by:cdebel
ID: 24396102
Mr Coulson, have you tried my solution?

>>I don't think I can use "BodyTag.Attributes.Add("onload", "javascript:(window.close())")"
>>because this window is already loaded.  Correct?

This is the beauty of PreInit.  In this method, the objects exists, but the no other events have been triggered yet.  So you can assign an event, and you will be sure that it will be triggered.

I use this method all the time.  Why reinventing the wheel?
0
 

Author Comment

by:mrcoulson
ID: 24396256
cdebel: I don't know how to implement your solution.  I already have a Response.Redirect.  Below is my attempt that did not work.  The redirect happens, but the close never does.  I guess I don't really understand how adding an action to onload of a window after it's already loaded will work -- maybe if it's somehow testing if the email form window is loaded...?


<script runat="server" language="vb">

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

End Sub

 

    Private Sub ScheduleEvent_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

        If Request.QueryString.Get("user") <> String.Empty Then

            BodyTag.Attributes.Add("onload", "javascript:(window.close())")

        End If

    End Sub
 

</script>

Open in new window

0
 
LVL 10

Expert Comment

by:cdebel
ID: 24396285
ok, give me a second, i'll implement it and send you a complete file...
0
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24396369
Okay, this is the last solution that I can offer:

On page load,

DIm URL as string = "/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString())
           
LinkButton1.Attributes.Add("onclick","opener.location.location=" & URL & "; window.close(); return false;")



This will change the parent window's location and close existing window.
0
 

Author Comment

by:mrcoulson
ID: 24396735
baiju_nagori:  'CommandArgument' is not a member of 'System.EventArgs'  Sure wish you could stick around!

Jeremy
<script runat="server" language="vb">
 

Public Sub page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

	Dim URL As String

	URL = "/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString())

   	LinkButton1.Attributes.Add("onclick","opener.location.location=" & URL & "; window.close(); return false;")

End Sub
 

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))

End Sub
 

</script>

Open in new window

0
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24396816
Sorry man, my bad with previous code You need to use the email address instead of commandargument

Public Sub page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim URL As String
        URL = "/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode("gary@garylofton.org")
        LinkButton1.Attributes.Add("onclick","opener.location.location=" & URL & "; window.close(); return false;")
End Sub

0
 

Author Comment

by:mrcoulson
ID: 24396903
Okay, man.  Here's where that is.

If I plug your function in and leave SetSessionVariable, the page just redirects with no close.

If I take the SetSessionVariable function away, the page throws an exception because that function is still referenced in the LinkButton.

If I removed OnCommand from the LinkButton, the link then just opens popBackCreek.aspx in another window without ever redirecting.

Jeremy
0
 
LVL 10

Accepted Solution

by:
cdebel earned 500 total points
ID: 24396904
MrCoulson... here's my version.
It's tested, and it work.

>>Actually, I'd really prefer it to open in the window that launched the pop-up,
>>but I believe I remember learning that it can't be done.

and this is the way it work too...  it open it in the window that launched the popup!
--- Code to place in CallerForm.aspx ---

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="CallerForm.aspx.vb" Inherits="Test_ASP.NET_App.CallerForm" %>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Button ID="btnCallFirstPopup" runat="server" Text="Button" OnClientClick="window.open('Popup2.aspx');" />

    </div>

    </form>

</body>

</html>
 

--- Code to place in Popup2.aspx ---

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Popup2.aspx.vb" Inherits="Test_ASP.NET_App.Popup2" %>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<html xmlns="http://www.w3.org/1999/xhtml">

 

<head id="Head1" runat="server">

<title>Back Creek Supervisor</title>

<link rel="shortcut icon" href="/FAVICON.ICO" type="image/x-icon" />

<style>

body {background-color: #ffffff;}

h2 {font-family: sans-serif;}

p {margin-right: 5%;}

.image {float: left; padding: 10px;}

.style1 {font-size: 18px}

</style>

<script type="text/javascript" src="/js/offsiteAlerter.js"></script>

</head>

<body id="BodyTag" runat="server">

    <form id="supervisorForm" runat="server">

        <h2>Back Creek  Magisterial District</h2>
 

        <div class="image">

            <p><span class="style171 style1"><strong>Gary A. Lofton</strong></span><br>

            711 Buffalo Marsh Road<br />Middletown, VA 22645

            <br>

            (540) 869-1972<br />fax (540) 869-1972<br />

            <asp:LinkButton ID="LinkButton1" runat="server" Text="Email Gary" CommandArgument="gary@garylofton.org" CommandName="SetSessionVariable" OnCommand="SetSessionVariable" /><br>

                

            <br>

            <span class="blurb">Gary Lofton was elected to the Board on January 1, 2008. </span></p>

            <p><span class="blurb">Mr. Lofton represents the Board as a member of the Human Resources Committee Chairman; Code &amp; Ordinance Committee; Social Services Board;  Planning Commission liaison; Agricultural District Advisory; and Extension Leadership Council.</span></p>

            <p><span class="blurb">Prior to his election to the Board, Mr. Lofton worked with VDOT for seven years and worked for the City of Winchester for 36+ years as Public Works Director and Director of Transportation. Mr. Lofton retired in 2006 and works as the Area Director for BNI-Shenandoah Valley.</span></p>

            <p><span class="blurb">He is a graduate of James Wood High School and attended Lord Fairfax Community College. </span></p>

            <center><p><input type=button value="Close Window" onClick="javascript:window.close();"></p></center>

        </div>

    </form>

</body>

</html>
 

--- Code to place in the Popup2.aspx.vb ---

Public Partial Class Popup2

    Inherits System.Web.UI.Page
 

    Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)

        Page.Response.Redirect("Popup2.aspx?action=close&email=" & e.CommandArgument.ToString())

    End Sub
 

    Private Sub Popup_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

        Dim s As String
 

        If Request.QueryString.Get("action") = "close" Then

            BodyTag.Attributes.Add("onload", "javascript:(window.close())")

            '"opener.location='/_User/Calendrier.aspx';"

            s = "opener.location='email_form_2.aspx?user=" & Request.QueryString.Get("email") & "';"

            BodyTag.Attributes.Add("onunload", s)

        End If

    End Sub

End Class

Open in new window

0
 
LVL 10

Expert Comment

by:cdebel
ID: 24396940
And about my last solution here are my comments:
- You need to open the first popup with the CallerForm.aspx.
- In the Popup2.apsx, i've removed an image because i didn't had it (lofton.gif)... you can place it back
- In Popup2.aspx, you have to make sure that you point to your own path.
so instead of having this:
s = "opener.location='email_form_2.aspx?user=" & Request.QueryString.Get("email") & "';"

you would have something like this:

s = "opener.location='/apps/email_form/email_form_2.aspx?user=" & Request.QueryString.Get("email") & "';"
0
 

Author Comment

by:mrcoulson
ID: 24396941
cdebel: Okay, let me try that out.  I need to put it all in the right place and get back to you.

Jeremy
0
 
LVL 10

Expert Comment

by:cdebel
ID: 24397068
If you tell me that this doesn`t work, please, download the whole solution here.  Its probably because you have made a mistake in copy&paste.
Download Solution
(This solution was made with Visual Studio 2005 Std)
0
 

Author Comment

by:mrcoulson
ID: 24398893
Still haven't had a chance to try this out.  In a meeting right now!  I'll get back to this as soon as I can!

Jeremy
0
 
LVL 10

Expert Comment

by:cdebel
ID: 24400311
good.  Just to save you some time, just download the solution.   Then if you want to apply it differently or need explanations on how it work, feel free to ask.  I'll be here...
0
 
LVL 10

Expert Comment

by:cdebel
ID: 24611854
it has been a month.   Did you had time to try it Jeremy?
0
 

Author Closing Comment

by:mrcoulson
ID: 31581654
Cleaning up old questions.  Thanks!  Sorry about the delay.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now