Click here to Skip to main content
15,881,613 members
Articles / Web Development / HTML
Article

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

Rate me:
Please Sign up or sign in to vote.
3.97/5 (24 votes)
8 Mar 20064 min read 265.1K   96   16
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:

SQL
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

C#
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.

HTML
<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:

Image 1

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.

HTML
<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.

C#
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:

C#
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:

Image 2

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.

C#
// 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:

HTML
<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:

HTML
<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


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
QuestionHow can I refresh? Pin
javierlinares16-Feb-10 9:39
javierlinares16-Feb-10 9:39 
QuestionGetting error of semicolon Pin
Archana9914-Feb-10 22:36
Archana9914-Feb-10 22:36 
GeneralFound another way for me Pin
gritsandcornbread8-Apr-09 10:33
gritsandcornbread8-Apr-09 10:33 
GeneralI am getting error:"Not enough storage is available to complete this operation." Pin
anil22kar25-Sep-08 3:45
anil22kar25-Sep-08 3:45 
GeneralBind the popup (web user control) with xml datatype in gridview row Pin
Member 21636969-Sep-08 9:32
Member 21636969-Sep-08 9:32 
QuestionDo the Opposite? Pin
raremother6-Mar-08 10:00
raremother6-Mar-08 10:00 
Generalgridview viewstate Pin
Member 376261719-Feb-08 13:01
Member 376261719-Feb-08 13:01 
Questionhow to refresh only grid view with out refreshing whole page Pin
c.sravanthi17-Sep-07 23:23
c.sravanthi17-Sep-07 23:23 
GeneralDoesn't Work on my Project Pin
mikem4214-Mar-07 4:20
mikem4214-Mar-07 4:20 
GeneralNo Subject Pin
whywhy295-Mar-07 16:32
whywhy295-Mar-07 16:32 
QuestionHow Can it Work with Dialog Window ? Pin
Latifa51914-Dec-06 7:24
Latifa51914-Dec-06 7:24 
AnswerRe: How Can it Work with Dialog Window ? Pin
azamsharp14-Dec-06 7:29
azamsharp14-Dec-06 7:29 
Generalcould your post all code for me?y1j1liang@sina.com Pin
y1j1liang12-Sep-06 3:22
y1j1liang12-Sep-06 3:22 
GeneralSome Corrections Pin
harrach6-Sep-06 2:21
harrach6-Sep-06 2:21 
QuestionCode as well ??? Pin
frederic.robert21-Jun-06 7:15
frederic.robert21-Jun-06 7:15 
QuestionCould you post the whole coding? Pin
zhuomiao.ma@bankofamerica.com2-Jun-06 6:10
zhuomiao.ma@bankofamerica.com2-Jun-06 6:10 

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

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