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

Comments

# re: Passing Data Between Parent and Child window

Thursday, April 05, 2007 10:16 AM by myChucky

Okay, I did an alert on:

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

And I got: Document lable 1: undefined

Any idea why?

# re: Passing Data Between Parent and Child window

Friday, April 06, 2007 6:53 AM by haissam

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

try

document.getElementById('lable1').innerText

Best Regards,

HC

# re: Passing Data Between Parent and Child window

Friday, April 06, 2007 11:50 AM by Anonymous

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.

# re: Passing Data Between Parent and Child window

Friday, April 06, 2007 4:49 PM by haissam

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

Try it by yourself !!!!

Best Regards,

HC

# re: Passing Data Between Parent and Child window

Saturday, April 07, 2007 4:35 PM by Julia

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.

# re: Passing Data Between Parent and Child window

Saturday, April 07, 2007 8:42 PM by haissam

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

# re: Passing Data Between Parent and Child window

Tuesday, April 10, 2007 6:34 PM by Julia

Hi ,

Thanks for concern..

It was an excellent idea ..

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

Best regards

Julia.

# re: Passing Data Between Parent and Child window

Wednesday, April 11, 2007 7:46 AM by Haissam

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

# re: Passing Data Between Parent and Child window

Thursday, April 12, 2007 3:01 PM by Julia

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

# re: Passing Data Between Parent and Child window

Thursday, April 12, 2007 6:03 PM by haissam

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

# re: Passing Data Between Parent and Child window

Wednesday, April 25, 2007 1:05 PM by Julia

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 .

# re: Passing Data Between Parent and Child window

Monday, May 14, 2007 8:11 AM by Micke

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

# re: Passing Data Between Parent and Child window

Saturday, May 26, 2007 11:04 PM by Hery

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

# re: Passing Data Between Parent and Child window

Thursday, May 31, 2007 4:22 PM by MorganEX

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

# re: Passing Data Between Parent and Child window

Saturday, June 23, 2007 2:13 PM by karbagamoorthy

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

# re: Passing Data Between Parent and Child window

Monday, July 30, 2007 3:08 AM by Ruci Antassani

Hi Haissam,

Can I change window.open with window.showModalDialog ?

If I can then show me how pls.

Regards,

Ruci Antassani

# re: Passing Data Between Parent and Child window

Tuesday, August 07, 2007 2:07 AM by Hamid

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

# re: Passing Data Between Parent and Child window

Wednesday, August 22, 2007 11:19 AM by haissam

Try to use the below javascript code

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

# re: Passing Data Between Parent and Child window

Wednesday, September 05, 2007 2:55 AM by a

thnks

# re: Passing Data Between Parent and Child window

Thursday, September 20, 2007 1:59 AM by santhosh

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

# re: Passing Data Between Parent and Child window

Thursday, September 20, 2007 2:02 AM by santhosh

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

# re: Passing Data Between Parent and Child window

Thursday, September 27, 2007 4:49 AM by madhu

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

# re: Passing Data Between Parent and Child window

Monday, October 01, 2007 3:03 AM by anshu kumar

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

# re: Passing Data Between Parent and Child window

Monday, October 01, 2007 3:08 AM by anshu kumar

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

# re: Passing Data Between Parent and Child window

Wednesday, October 10, 2007 2:38 AM by Arjun

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

# re: Passing Data Between Parent and Child window

Friday, October 12, 2007 3:50 PM by Kash

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?

# re: Passing Data Between Parent and Child window

Tuesday, December 11, 2007 11:12 AM by Dhiyani

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

# re: Passing Data Between Parent and Child window

Tuesday, December 18, 2007 11:57 AM by Chandru

Pls hlp me out.

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

# re: Passing Data Between Parent and Child window

Thursday, January 03, 2008 1:59 AM by draynos

thanks HC. Got it!!!!

# re: Passing Data Between Parent and Child window

Friday, January 04, 2008 2:18 AM by Vineet Kumar Srivastava

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.

# re: Passing Data Between Parent and Child window

Tuesday, January 08, 2008 4:28 AM by Rohit * Amol M

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

# re: Passing Data Between Parent and Child window

Tuesday, January 08, 2008 5:01 AM by Venkat

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

# re: Passing Data Between Parent and Child window

Sunday, January 27, 2008 2:25 AM by Sunitha

Hi Haissam and Julia,

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

Thanks a lot.

# re: Passing Data Between Parent and Child window

Friday, February 01, 2008 8:21 AM by Sajan

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

# re: Passing Data Between Parent and Child window

Tuesday, February 05, 2008 11:23 PM by Ravish

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

# re: Passing Data Between Parent and Child window

Wednesday, February 06, 2008 5:05 AM by Jebahar Deva Dhason D R

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

# re: Passing Data Between Parent and Child window

Friday, February 08, 2008 11:44 AM by Mohit bansal

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

# re: Passing Data Between Parent and Child window

Tuesday, February 12, 2008 1:34 PM by suma

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

# re: Passing Data Between Parent and Child window

Wednesday, February 13, 2008 6:21 AM by haissam

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

# re: Passing Data Between Parent and Child window

Wednesday, February 13, 2008 7:01 AM by haissam

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

# re: Passing Data Between Parent and Child window

Wednesday, February 13, 2008 11:24 AM by suma

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

# re: Passing Data Between Parent and Child window

Wednesday, February 27, 2008 11:10 AM by Andy Nguyen

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.

# re: Passing Data Between Parent and Child window

Tuesday, March 11, 2008 6:37 AM by Evil Inside

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

Pingback from  posting form data from child window to parent javascript

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.