Pages

Thursday, April 23, 2009

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

I found this article in CodeProject

We can refresh a GridView control on the parent page, from a pop up window.

We use a 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.








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






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




";

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



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:


Also keep in mind that you don't have to register any scripts when you are using opener.location.reload().





0 comments:

Post a Comment