The scenario for today’s blog post is pretty simple. I have a page that is displaying some data, and it uses a pop-up window to add data to the source, so when the pop up has added the data it needs to close itself and then refresh the parent window. It’s not really a difficult thing to do, lets have a look at the code.
In your parent window, add a LinkButton that has an empty text property. Then in the click event of this button, put in the logic that refreshes your data. When you look at the page, you shouldn’t see the link at all, but if you have a look at the source code, you will see the <A> tag for it is on the page.
In your pop-up window, in whatever method is adding the data to your source, add the following code:
1: String js = "window.opener.__doPostBack('ControlsUniqueId', '');" + Environment.NewLine;
2: js += "window.close();" + Environment.NewLine;
3:
4: Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "WindowClose", js, true);
This will tell the parent window to do the post back caused by LinkButton we added to the parent page, so your refreshing logic will run. In place of the "ControlsUniqueId" you should put in the UniqueId property of the LinkButton on the parent page. I pass this as a query string parameter to the pop up window, so it knows what control to call the post back as.
Once this is all in, when you run the code, whenever your pop up runs the code that will save your data, it will also then close and refresh your parent window. It’s that easy! At this point I have only tested this in Internet Explorer, so I can’t say for sure that it will work in other browsers, but if it doesn’t it’s just a matter of finding how to call the postback of the window.opener property.
Also, be aware that if your users have JavaScript disabled (for whatever reason) your window won’t close and the main window will not refresh, so if you are trying to make a completely accessible version of the page you will want to give some thought to how you could achieve this.