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