Introduction
In this article, I will show you how to can refresh a GridView control on the parent page, from a pop up window. I will discuss different scenarios which you will find very helpful when implementing your solution.
Database Table
I will be using my own custom table for this article. The table name is Users, and it contain columns for UserID, UserName, FirstName, and LastName. UserID is an automatically generated primary key. Here is the schema of the Users table:
if exists (select * from dbo.sysobjects where
id = object_id(N'[dbo].[Users]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Users]
GO
CREATE TABLE [dbo].[Users] (
[UserID] [int] IDENTITY (1, 1) NOT NULL ,
[UserName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FirstName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[LastName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
Making the Parent Page
The parent page will contain a GridView control and a href tag. The href tag will open a new popup window which will be used to insert the data into the database and refresh the GridView control which is contained in the parent page. Let's see how the parent page is implemented.
Code-Behind of the Parent Page
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
string query = "SELECT * FROM Users";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Users");
GridView1.DataSource = ds;
GridView1.DataBind();
}
private string ConnectionString
{
get { return @"Server=localhost;Database" +
@"=MyDatabase;Trusted_Connection=true"; }
}
As you can see, I am not doing anything fancy. I simply populate the GridView from the database, using a SELECT query in the BindData method.
The parent page also contains the href tag which is used to open the popup window. Let's see the code for this href tag in the HTML view of the page.
<a href="#" onclick="OpenWindow()">Insert Data
<script language="javascript" type="text/javascript">
function OpenWindow()
{
window.open ("PopUpWindow.aspx",
"mywindow", "menubar=0,resizable=0," +
"width=350,height=250,toolbars=0");
}
</script>
Pretty simply, right? The OpenWindow function is fired when you click on the href tag. This will open a small pop up window. Take a look at the screenshot below to have a clear idea:

Yes, you have guessed right, the small window which contains the textboxes for user name, first name, and last name is our small popup window. Now, after filling all the required information in the textboxes and pressing the Add User button, we want it to add the user to the database and refresh the parent page which contains the GridView control, hence populating the newly inserted data into the GridView.
Implementation of the Popup Page
Now, let's see that how the popup page is implemented. First, let's see the HTML code for the popup page so we will know how the controls are setup on the page.
<form id="form1" runat="server">
<div>
UserName: <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br>
FirstName:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br>
LastName:<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br>
<asp:Button ID="BtnAdd" runat="server" Text="Add User" OnClick="BtnAdd_Click"/>
<asp:Button ID="Btn_CloseWindow" runat="server" Text="Close Window"/>
</div>
</form>
Now, let's implement the code that will insert the data into the database. The following code is triggered when the user presses the "Add User" button.
private void AddUser(string userName, string firstName, string lastName)
{
string QUERY_ADDUSER = @"INSERT INTO Users(UserName," +
@" FirstName, LastName) VALUES(@UserName,@FirstName,@LastName)";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand(QUERY_ADDUSER, myConnection);
myCommand.Parameters.AddWithValue("@UserName", userName);
myCommand.Parameters.AddWithValue("@FirstName", firstName);
myCommand.Parameters.AddWithValue("@LastName", lastName);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
The above code simply attaches the parameters to the parameterized query and inserts them into the database. I am pretty sure you have done similar stuff several times.
Now, let's see the code that will refresh the parent page which contains the GridView.
Refreshing the GridView Control on the Parent Page
Refreshing the GridView control on the parent page sounds refreshing! Sorry about the bad joke, let's get to the point. Refreshing the GridView control is pretty simple. Take a look at the code below:
protected void Page_Load(object sender, EventArgs e)
{
string scriptString = "<script language="JavaScript"> " +
"window.opener.document.forms(0).submit(); </script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}
if (!Page.IsPostBack) { }
}
I have included the code for both the versions. The commented out code can be used if you are using Visual Studio .NET 2003 or the .NET framework 1.X. All I am doing in the page load event is, attaching the client side script to the page. The script window.opener.document.forms(0).submit(); means that the parent of the current page will be submitted. This will cause a postback to happen on the parent page, and since we are binding the GridView control on every page load, it will work fine. Take a look at the screenshot below:

So, you see, it is pretty simple, right? Now, let's take care of some important things. Let's say that you want to close the window when the "Close Window" button is pressed. You can do this by simply attaching the JavaScript "window.close()" function to the button click event.
Btn_CloseWindow.OnClientClick = "window.close();";
Btn_CloseWindow.Attributes.Add("onclick", "window.close();");
You might want to attach the window close event to the "Add User" button. This way, when the user is added, the popup window is automatically closed. For this, you can use the OnUnload event. Check out the code below:
<body onunload="opener.location.reload();">
As I already explained, the JavaScript function window.opener.document.forms(0).submit(); will cause a postback, and in order to work with this example, you need to bind the GridView each time the page is loaded. This is not a good idea, and you can improve that by using the opener.location.reload(); function which will reload the parent page. This way, you can bind the GridView and other controls only when the page is reloaded and not if there is a postback. In order to use opener.location.reload();, simply attach it to the OnUnload event of the parent page, as shown below:
<body onunload="opener.location.reload();">
Also keep in mind that you don't have to register any scripts when you are using opener.location.reload().
I hope you liked this article, happy coding!
|
|
 |
 | How can I refresh? javierlinares | 10:39 16 Feb '10 |
|
 |
Hello i´ve got a question. I´d like to know how can i refresh Gridview from Fromview in ASP.Net. And if is posible in Visual Basic too.
|
|
|
|
 |
 | Getting error of semicolon Archana99 | 23:36 14 Feb '10 |
|
 |
when i am trying to run this application in vs 2008. i found one error in the page_load of parent page that semicolon is expected near javascript tag. cn ny1 pls help me out..
|
|
|
|
 |
 | Found another way for me gritsandcornbread | 11:33 8 Apr '09 |
|
 |
In my case, i needed to databind a control on my parent form based on input from a popup but didn't want to deal with postbacks to do my data binding. Also, I could not just reload the parent form because my binding in my data grid was tied the users selection in a drop down list. SO... the binding that occurs onpage load is using query string variables to set my drop down and then binding would occur. But if the user changes the selection in the drop down, the grid is rebound again. I didn't want to reload the form back to the original selection after closing my popup. CLear as mud???
to make a long story longer, I stumbled across the replace function seen below:
window.opener.location.replace(URL goes here)
and in my case (code on my popup page):
Response.Write("<script language="Javascript">window.opener.location.replace('ClearanceForm.aspx?n=" & Request.QueryString("n") & "&ct=" & Request.QueryString("ct") & "');window.close();</script>")
Since I passed the query string variables to my popup, I'm able to simply replace the URL on the parent page with those same values. This is kind of like a reload but I know that my drop down selection will be set correctly on the parent form and not reset to what it was originally when the form was opened.
I know this will not work for all cases - but just wanted to let people know that it may be another alternative to accomplish the same task.
|
|
|
|
 |
 | I am getting error:"Not enough storage is available to complete this operation." anil22kar | 4:45 25 Sep '08 |
|
 |
Hi azamsharp,
I am using same thing what is discussed here in my parent & child form.
I am getting error:"Not enough storage is available to complete this operation."
Also it gives "Delay Notification" pop up window which halts my browser.
On parent page, I have a gridview which loads new data after processing of child page process. The code is like this:
function Close() { window.opener.document.forms[0].submit(); window.close(); return true; }
Will u pls help me.
Anil J Baviskar
|
|
|
|
 |
 | Bind the popup (web user control) with xml datatype in gridview row Member 2163696 | 10:32 9 Sep '08 |
|
 |
Hi,
I am having one gridview(.NET 2.0) which i am binding with objectdatasource.The table in which one field is xml data type. The purpose of the xml data type is to bind the web user control which consist of two dropdown,one textbox,Remove button,Add button). Means user can create dynamically a set of control for a gridviewrow.What i want to implement, user can enter for each gridview row , multiple customers,category and percentage combination.
I want to bind the webusercontrol value property with xml data type.And I want to set the selectedvalue property of the dropdown,when user clicked again popup to show what user has selected.
Please let me know how can I bind web user control with the xml.
Raj
Rajesh Kumar Verma
|
|
|
|
 |
 | Do the Opposite? raremother | 11:00 6 Mar '08 |
|
 |
I want to do the opposite..I want my Parent page to STOP changing its own font when it launches the Popup! Does anybody have that problem? When I click the gridview link to open a Popup page, the Popup page works fine, but for some reason my parent page repaints, and LOSES its font styles! The fonts get about twice as large. Any suggestions?
REJ
|
|
|
|
 |
 | gridview viewstate Member 3762617 | 14:01 19 Feb '08 |
|
 |
One thing I came across that I hope helps some one else. The view state of the gridview should be set to false, I think it's normally true. Or at least that is the case when you are using master pages. Hope this saves some one from some very painful headbanging.
|
|
|
|
 |
 | how to refresh only grid view with out refreshing whole page c.sravanthi | 0:23 18 Sep '07 |
|
 |
how to refresh only grid view with out refreshing whole page?
scenario: i am using a registration page where use enter some data like name, address and for qulification i used to opena popup window and accept multiple skills/qualifications and bind to data table and saved in a session.
when this popup window is closed using window.close() and written <body onunload="opener.location.reload();" > in the child page. which makes refresh of whole page whenever a record is saved to session and gridview in parent page is binded to datatble in the session.
but this makes loss of data in parent page which already entered by the user.
how to resolve this?
C.L.sravanthi
|
|
|
|
 |
 | Doesn't Work on my Project mikem42 | 5:20 14 Mar '07 |
|
 |
A second copy of the parent window opens and closing the popup doesn't refresh either copy of the parent.
Mike
|
|
|
|
 |
 | whywhy29 | 17:32 5 Mar '07 |
|
 |
hi, can i have the full coding ?
Samantha email:whywhy29@yahoo.com.sg
|
|
|
|
 |
 | How Can it Work with Dialog Window ? Latifa519 | 8:24 14 Dec '06 |
|
 |
Excellent Article. But I tried what you said with a parent window having a Dialog Window as a child but it didn't work. Can Help me and tell me How can I do this with a Dialog window? Thanks.
Latifa E-mail:latifa519@hotmail.com
|
|
|
|
 |
|
 |
Hi,
I will try it out and let you know.
Thanks, AzamSharp
Mohammad Azam azamsharp@gmail.com www.gridviewguy.com videos.gridviewguy.com
Houston, TEXAS
|
|
|
|
 |
 | could your post all code for me?y1j1liang@sina.com y1j1liang | 4:22 12 Sep '06 |
|
 |
could your post all code for me?y1j1liang@sina.com
y1j1liang
|
|
|
|
 |
 | Some Corrections harrach | 3:21 6 Sep '06 |
|
 |
Salaam Alaikum!
Nice article. But there's one mistake I need to point at. The part where you explain how to refresh the GridView control on the parent page is a bit wrong. You see, the "window.opener.document.forms[0].submit()" function should be called from the child window (the pop-up), so its "opener" form (parent window) gets submitted (reloaded).
Also, you didn't mention that if you use the "submit()" function validation on the parent page will be triggered. If you don't want the page to be validated there's a little trick that works only for IE. It is the "execScript" function. Basically, it gives you the ability to execute a script from a remote window. To make use of it, create a control on the parent page that has "CausesValidation" set to false. I used a link button with the "Text" property set to "" (note that if you set the control to be invisible you won't be able to call it). Of course, the link button should not point to any URL or have any events associated. After that, just put the following code in the child window's code behind:
refreshScript = "<script language='javascript'> window.opener.execScript(\"__doPostBack('LinkButton1','')\",\"JavaScript\")</script>"; ClientScript.RegisterStartupScript(typeof(string), "RefreshScript", refreshScript);
Note that if you have renamed the link button (or any control) you'll need to enter that same ID into the "__doPostBack" call.
I previously stated that this works only for IE. In order to refresh pages in other browsers you'll need the old-style "window.opener" method to be used. So, my code looks like this:
string refreshScript = ""; if (Request.Browser.Browser != "IE") refreshScript = "<script language='javascript'> window.opener.document.forms[0].submit()</script>"; else refreshScript = "<script language='javascript'> window.opener.execScript(\"__doPostBack('LinkButton1','')\",\"JavaScript\")</script>"; ClientScript.RegisterStartupScript(typeof(string), "RefreshScript", refreshScript);
Note that instead of the usual brackets () I'm using [] in my code. That's another incompability issue. If you use the () brackets Firefox, for instance, won't refresh the parent page at all.
I hope this'll help somebody out there.
.: Shall I push the button? :.
|
|
|
|
 |
 | Code as well ??? frederic.robert | 8:15 21 Jun '06 |
|
 |
Hello,
Is it possible to receive an URL to download the whole code please ?
Thanks
Frederic
|
|
|
|
 |
 | Could you post the whole coding? zhuomiao.ma@bankofamerica.com | 7:10 2 Jun '06 |
|
 |
could you let us download your whole code?
Thanks,
Michael
|
|
|
|
 |
|
|
Last Updated 8 Mar 2006 |
Advertise |
Privacy |
Terms of Use |
Copyright ©
CodeProject, 1999-2010