Passing Data Between Parent and Child window

In this blog post, i will show you a working example of how to open a popup window, do some processing and send the information back to the parent window.

First create a webform, in this example it's called WebForm1.aspx containing a textbox (txtPopResult). On it's page_load event, we will create an arraylist holding values from 0 to 9, save it in a session variable, and finally opening Popup.aspx in new window.

WebForm1.aspx

   private void Page_Load(object sender, System.EventArgs e)
  {
   // Create new instance of ArrayList object
   ArrayList al = new ArrayList();

   // loop to add values from 0 till 9 in the arraylist
   for(int i=0;i<10;i++)
   {
    al.Add(i);
   }

   // Save it in a Session variable
   Session["Array"] = al;

   // Open Popup window with a specified width and height.
LINE1:   Page.RegisterStartupScript("openpopup","<script language=javascript>window.open('Popup.aspx','test','height=200px;width=300px');</script>");
  }

Now the popup window will open, it contains a dropdownlist to hold the values of the Arraylist saved in the session variable. After the user selected an item from the dropdownlist, it will be saved inside the textbox (txtPopResult) in the parent window and it will be closed. To implement this functionality, we will add code to page_load event to fill the dropdownlist with the arraylist values. and we will handle the SelectionChanged of the dropdownlist.

Popup.aspx


    private void Page_Load(object sender, System.EventArgs e)
  {
   // Get the Array list from the session variable
   ArrayList al = (ArrayList)Session["Array"];
   
   // loop through arraylist items and add them to the dropdownlist.
   for(int i=0;i<al.Count;i++)
   {
    DropDownList1.Items.Add(i.ToString());
   }
}

 private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   string selectedValue = DropDownList1.SelectedItem.Text;
LINE2:   Page.RegisterStartupScript("close","<script language=javascript>window.opener.document.getElementById('txtPopResult').value = '"+selectedValue+"';self.close();</script>");
  }

The code above in bold will set the textbox control in the parent window to the value selected by the user from the dropdownlist

N.B:  Line numbers are added for reference use only throughout this example.

 For ASP.NET 2.0 you should modify Line2 by the below code

 Page.ClientScript.RegisterStartupScript(this.GetType(),"close","<script language=javascript>window.opener.document.getElementById('txtPopResult').value = '"+selectedValue+"';self.close();</script>");

and Line1 by the below code

Page.ClientScript.RegisterStartupScript(this.GetType(),"openpopup","<script language=javascript>window.open('Popup.aspx','test','height=200px;width=300px');</script>");

Hope it helps you.

Best Regards,

HC

Published 03 April 2007 06:57 AM by haissam

Comments

# myChucky said on 05 April, 2007 10:16 AM

Okay, I did an alert on:

alert("Document lable 1: " + document.getElementById('lable1').value)

And I got: Document lable 1: undefined

Any idea why?

# haissam said on 06 April, 2007 06:53 AM

To get the label text, you need to use the innerText and not value

try

document.getElementById('lable1').innerText

Best Regards,

HC

# Anonymous said on 06 April, 2007 11:50 AM

It says lable is not defined, Haissam!

It doenst matter what property he tries to set, he will get the same error.

Make sure you are spelling the element ID correctly, chucky.

# haissam said on 06 April, 2007 04:49 PM

Not the label is undefined, the value is undefined. so the .innerText should work.

Try it by yourself !!!!

Best Regards,

HC

# Julia said on 07 April, 2007 04:35 PM

Hi Haissam ,

if the parent page has connected with master page ....

how can I rach it ??? by document aslo !!!

what if the textBox that I want to return value on it ... is inside server control ... >>> how can I insert on it ???....

:)

Hop fine an answer for these questions..

Julia.

# haissam said on 07 April, 2007 08:42 PM

When using a Master page, the textbox id is generated by asp.net. that is why window.opener.document.getElementById('TextBox1').value never works. However i have found a way to enable you to set the textbox value in the parent page if it was with masterpage.

Create a hidden textbox on the popup window which will hold the id of the textbox inside the parent page.  Below is the Code behind (The textbox in the parent page is called TextBox2 and the textbox on the popup window is called TextBox1)

string textboxId = TextBox2.ClientID;

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "openwindow", "<script language=javascript>var popup = window.open('Default.aspx','popup','');popup.setTimeout('if(document.getElementById(\"TextBox1\")!=null) { document.getElementById(\"TextBox1\").value = \"" + textboxId + "\";}',300);;</script>");

Now the textbox1 in the popup page contains the ID of the textbox in the parent page, and using the code below you can set it's value

Button1.Attributes.Add("onclick", "var textbox = document.getElementById('TextBox1').value;window.opener.document.getElementById(textbox).value = '123';");

HC

# Julia said on 10 April, 2007 06:34 PM

Hi ,

Thanks for concern..

It was an excellent idea ..

But unfortunately does not work with me >>> I do not know why ??

Best regards

Julia.

# Haissam said on 11 April, 2007 07:46 AM

You can go for an easier way, before you open your page using Page.ClientScript, save the textbox id in a session variable and when you want to set from the popup page the value of the textbox you can retrieve it's id from the session

// Save it into Session

Session["TestBoxID"] = TextBox1.ClientID;

Page.ClientScript.RegisterStartUpScript(This.GetType(),"open","window.open('WebForm2.aspx');",true);

and now in your popup window use

string TextBoxID = Session["TextBoxID"];

Button1.Attributes.Add("onclick","window.opener.document.getElementById('"+TextBoxID+"').value = '123'; window.close();");

This way will work for sure

Best Regards,

HC

# Julia said on 12 April, 2007 03:01 PM

Hi,

I am sorry >> but it does not work with me ..

Thanks for trying to help me for the second time..

God bless you.

Julia

# haissam said on 12 April, 2007 06:03 PM

Julia,

You are most welcome, if you want me to help you more please don't hesitate to send me an email with a description of what you are trying to achieve and the code you are using so i can trace it and send you the solution.

Best Regards,

HC

# Julia said on 25 April, 2007 01:05 PM

Hi Hissam ,

I am sorry for late..

Some of the programmer told me about technique I can use it to solve this problem ,, and it is work with me !.

Anyway, that is technique is :-

1)

On the Parent page write this script with asp.net code…

<script type="text/javascript" >

   function UploadFile()

{window.open('Popup.aspx','','alwaysLowered=yes,alwaysRaised=yes,left=400, top=100, height=500, width= 500, status=n o, resizable= no, scrollbars= no, toolbar= no,location= no, menubar= no');}

   function PopUpWindowCallBack(returnValue)  {document.getElementById('<%=FormView.FindControl("PicTextBox").ClientID %>').value=returnValue; }

   </script>  

Then on the button that open pop window..

Put this value on these attribute:-

OnClientClick = UploadFile();

UseSubmitBehavior= False

2)

On The PopUp  window …

Add following code to vb.net code :-

Dim a as integer = 33

CloseButton.Attributes.Add("onclick", "window.opener.PopUpWindowCallBack('" + a + "');window.close();")

Respectfully,

Julia .

# Micke said on 14 May, 2007 08:11 AM

Thanks Julia for your post works like a charm. Have been trying to figure this thing out fore a couple of days now when i found your code.

Thx Micke

# Hery said on 26 May, 2007 11:04 PM

Hi  haissam.

I have been trying  used a popup calendar but in my parental page I'm use a master page and i can't return the datetime selected :( the sourcecode is very simple, the code in the child page is:

function ReturnDate()

       {

        window.opener.document.forms[0].elements["<%= strCtrlName %>"].value= "<%= strSelectedDate %>";

        window.close();

       }

   function Close()

       {

           window.close();

       }

I have the same code without master page and the code working!!! but when a used master page  the things change :(

sorry for my bad english :p.....

thanks-Gracias

# MorganEX said on 31 May, 2007 04:22 PM

Haissam,

I have been working 4 days on trying to pass values back and forth with C# and ASP.NET (and yes, MasterPages).

Setting the Session["TextBoxID"] = TextBox1.ClientID finally did the trick for me.  Having a form in the MasterPage was hanging me up.

Thanks a ton for the idea!

-Morgan

# karbagamoorthy said on 23 June, 2007 02:13 PM

i am trying to use the pop-up calendar using master page,i couldn't able to return the selected date value.

thanks & advance,

DK Moorthy

# Ruci Antassani said on 30 July, 2007 03:08 AM

Hi Haissam,

Can I change window.open with window.showModalDialog ?

If I can then show me how pls.

Regards,

Ruci Antassani

# Hamid said on 07 August, 2007 02:07 AM

Hello! I am using a popup window in a project that has master pages, but I am getting an error when I try to pass a value from a textbox in the popup window.

Here is my code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="child.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

   <title>Untitled Page</title>

   <script  type="text/javascript">

   function sendInfo()

   {

   var childvalue = window.document.formchild.txtChild.value;

   window.opener.document.form1.txtparent.value= childvalue

   }

   </script>

</head>

<body>

   <form id="formchild" runat="server">

   <div>

       <asp:TextBox ID="txtChild" runat="server"></asp:TextBox>

       <input type="button" name="text1" onclick="sendInfo()" />

        </div>

   </form>

</body>

</html>

it's not recognizing the id of the textbox in the parent form.  Thanks for the help

# haissam said on 22 August, 2007 11:19 AM

Try to use the below javascript code

window.opener.document.getElementById('<%=txtparent.ClientID%>').value = childvalue

# a said on 05 September, 2007 02:55 AM

thnks

# santhosh said on 20 September, 2007 01:59 AM

Hi Haissam,

          i gone through your above example.

Inspite of Textbox in parent window, i placing the listbox in parent window how do i get the value from child.

Please give you idea on this.

Regards

santhosh

# santhosh said on 20 September, 2007 02:02 AM

Hi Haissam

Page.RegisterStartupScript( "close", "<script language=javascript>window.opener.document.getElementById(ListBox.options.add(new Option('" + selectedVale + "')');self.close();</script>" );

I didnt get the result

please give up your idea

# madhu said on 27 September, 2007 04:49 AM

hi i want to retrive a set of record ids as arraylist to the parent window in the form of arraylist how can we do that

# anshu kumar said on 01 October, 2007 03:03 AM

excelent .i got idea for gettig value in case of master page

# anshu kumar said on 01 October, 2007 03:08 AM

hi  i want to get the id of textbox which is in edit itemtemplate of gridview .actualy i want to pass this textbox id in javascript datetimepicker so that i can get date in gridview textbox .please help me

# Arjun said on 10 October, 2007 02:38 AM

Hi,

I am coming to this forum for the first time, Appreciate it.

One concern with me is, can we access a control in the child from the master page?

Thanks in advance.

Arjun

# Kash said on 12 October, 2007 03:50 PM

I can not seem to make the value return or the popup window close when i am using the above code. Do you have any suggestions?

# Dhiyani said on 11 December, 2007 11:12 AM

Hi Friends,

Same problem...

Pls hlp me out...

i need to pass values from Pop-up window to main window...pls give me the exact solutions...

Hope u hlp me..Thanks in advance...

# Chandru said on 18 December, 2007 11:57 AM

Pls hlp me out.

I also need pass mutliple values from parent window to popup window.

# draynos said on 03 January, 2008 01:59 AM

thanks HC. Got it!!!!

# Vineet Kumar Srivastava said on 04 January, 2008 02:18 AM

I think der is no other way except using 'session' in master child case.

I m facing this problem now-a-days but didn't get any solution.

I will let you know if i got something new.

Thanks.

# Rohit * Amol M said on 08 January, 2008 04:28 AM

Thanks, this code helps me lot.....

# Venkat said on 08 January, 2008 05:01 AM

Hi,

 I am venkat,I have one problem with passing data into popup window.I am using C#.net.i have soem values .

  the below line of code is working with parent page.But i want to show it in popup window.

textbox1.Text += "<BR><B>" + layer.getItem(i) + "</B>=" + shape.getValue(i);

the above line an example how i am getting the data.

can any one help me for this issue.

advanced thanks.

Regards

Venkat.

ven.tammineni@gmail.com

# Sunitha said on 27 January, 2008 02:25 AM

Hi Haissam and Julia,

This article was very very usefull for me. It solved my biggest problem.

Thanks a lot.

# Sajan said on 01 February, 2008 08:21 AM

Hi,

i am sajan.. i want pass the value between the parent and child window..you are using window.open instanted i am using window.showModalDialog()..

Help me..

Thanks & Regards,

S.Sajan

# Ravish said on 05 February, 2008 11:23 PM

I want to pass data from parent window to child ho can I do it without using query string?

# Jebahar Deva Dhason D R said on 06 February, 2008 05:05 AM

Dear Sajan,

I hope you know that you can pass an argument to the showModalDialog() method that gets called from the parent window.

For example, the following code will help you:

Parent window's page:

===================

var obj = window.document;

var retVal = window.showModalDialog("ModalDialogPage.aspx",obj,'dialogHeight: 155px; dialogWidth: 484px; dialogTop: 200px; dialogLeft: 200px; edge: Raised; center: Yes; help: No; resizable: No; status: No;');

Now, in the Modal Dialog's page:

==================================

var parentDoc = window.dialogArguments;

Now get the value as normal:

parentDoc.getElementById("ParentPageControl").value="Your new value";

# Mohit bansal said on 08 February, 2008 11:44 AM

hey can we send data to server side code from parent to child

# suma said on 12 February, 2008 01:34 PM

Hello Haissam,

I have a common popup for different searches like for example if u r searching for a country name in different pages so my issue is to get the value from the textbox i must and should have to use same textid in all the pages is there any way to give the different names for textbox in different pages and still use the same popup. please let me as soon as possible. let me know if i am not clear.

Thanks

Suma

# haissam said on 13 February, 2008 06:21 AM

Mohit bansal below is a link which will give you a closer idea of "Ways to pass data between webforms"

dotnetslackers.com/.../ways-to-pass-data-between-webforms.aspx

# haissam said on 13 February, 2008 07:01 AM

suma You can send the country name to the child window by using the querystring. i'm not getting why you need the same textbox id on all ur pages! if there is something you need to clear for me, it would be better.

Page.RegisterStartupScript("openpopup","<script language=javascript>window.open('Popup.aspx?countryName=' + '"+TextBox1.Text+"','test','height=200px;width=300px');</script>");

In the above, we sent the textbox1 text to the Popup page through querystring. In popup.aspx.cs you could retrieve it using

string countryName = Request.QueryString["countryName"];

Hope this helps

# suma said on 13 February, 2008 11:24 AM

Haissam

i have

popupwindow=window.open("../WebForms/countryname.aspx?page=&parentCall=true", "countryname","scrollbars=1,menubar=0,toolbar=0,location=0,status=0,width=800,height=460,resizable=yes");

in my parent page

if(document.getElementById( "txtABC" ).value == "")

           {

           //document.getElementById( "txtcountry" ).value = window.opener.document.Form1.txtcountry.value;

           document.getElementById( "txtcountry" ).value = eval("window.opener.document.Form1." + page + "txtcountry.value");}

Is there any other way of getting values instead of using getelementbyid

Please help me Haissam as soon as possible.

Thanks

Suma

# Andy Nguyen said on 27 February, 2008 11:10 AM

Here is how to send value back to parent page with MasterPage.

In the javacript that open the pop up windows,instead of sending the TextBox.ID to popup page, change it to TextBox.ClientID.

It work for sure.

# Evil Inside said on 11 March, 2008 06:37 AM

I have works with that but i got problem with that while using with master page.

# posting form data from child window to parent javascript said on 13 June, 2008 07:05 PM

Pingback from  posting form data from child window to parent javascript

# fdepijper@ziggo.nl said on 17 January, 2009 11:25 AM

Why not use a GUID which represents the data to pass between master and child..

Create a class which holds all parameters you need to pass between master and child page.

Serialize the class..

Store the class in a Session Variable with the GUID as the name.

Open the child window with a query string containing the PageID GUID..

Retrieve the class from the session variable..

this way you can pass all kinds of information between master and child both ways..

Besides it is also 100% secure since the clinet only gets the PageID GUID, the rest of the data is not sent to the client but remains in the view state..

Hope this helps.

This site

Search

Go

This Blog

Syndication

Sponsors

  • MaximumASP
  • Breaking News
  • Find a Job
  • Social Bookmarking
    Tidebuy Reviews
    Online Shopping
    asp.net hosting
    UK online local dating