Click here to Skip to main content
Click here to Skip to main content
Go to top

Refresh a GridView control on the parent page, from a pop up window

, 8 Mar 2006
Rate this:
Please Sign up or sign in to vote.
This article describes how to refresh a GridView control on the parent page, from a pop up window.

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()
{
  // make the query
  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</A><DIV></DIV>

<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>";

  // ASP.NET 2.0
  if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
  {
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
                                       "script", scriptString);
  }

  //// ASP.NET 1.X
  //if (!Page.IsClientScriptBlockRegistered(scriptString))
  //{
  // Page.RegisterClientScriptBlock("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.

// ASP.NET 2.0
Btn_CloseWindow.OnClientClick = "window.close();";

// ASP.NET 1.X
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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

azamsharp
Web Developer
United States United States
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop

Comments and Discussions

 
QuestionHow can I refresh? Pinmemberjavierlinares16-Feb-10 9:39 
QuestionGetting error of semicolon PinmemberArchana9914-Feb-10 22:36 
GeneralFound another way for me Pinmembergritsandcornbread8-Apr-09 10:33 
GeneralI am getting error:"Not enough storage is available to complete this operation." Pinmemberanil22kar25-Sep-08 3:45 
GeneralBind the popup (web user control) with xml datatype in gridview row PinmemberMember 21636969-Sep-08 9:32 
QuestionDo the Opposite? Pinmemberraremother6-Mar-08 10:00 
Generalgridview viewstate PinmemberMember 376261719-Feb-08 13:01 
Questionhow to refresh only grid view with out refreshing whole page Pinmemberc.sravanthi17-Sep-07 23:23 
GeneralDoesn't Work on my Project Pinmembermikem4214-Mar-07 4:20 
General Pinmemberwhywhy295-Mar-07 16:32 
QuestionHow Can it Work with Dialog Window ? PinmemberLatifa51914-Dec-06 7:24 
AnswerRe: How Can it Work with Dialog Window ? Pinmemberazamsharp14-Dec-06 7:29 
Generalcould your post all code for me?y1j1liang@sina.com Pinmembery1j1liang12-Sep-06 3:22 
GeneralSome Corrections Pinmemberharrach6-Sep-06 2:21 
QuestionCode as well ??? Pinmemberfrederic.robert21-Jun-06 7:15 
QuestionCould you post the whole coding? Pinmemberzhuomiao.ma@bankofamerica.com2-Jun-06 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 8 Mar 2006
Article Copyright 2006 by azamsharp
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid