Passing value from popup window to parent form's TextBox

Once again seen lot of questions on the forum related to passing values from popup window to the parent form textbox. Specially when they have some GridView type control in the popup. In the following example I will be using two forms, parent form will be parent.aspx and popup will be popup.aspx. Also note that my parent.aspx form is derived from some MasterPage. Code is provided both in VB.Net and C#.Net.

--- .aspx of parent form ---

<script type="text/javascript">
        function OpenPopup()
        {
            window.open("popup.aspx","List","scrollbars=no,resizable=no,width=400,height=280");
            return false;
        }
</script>
.
.
.
<asp:TextBox ID="txtPopupValue" runat="server" Width="327px"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Show List" />

--- .vb of parent.aspx if vb.net is the language ---

If Not IsPostBack Then
 Me.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()")
End If

--- .cs of parent.aspx if C#.net is the language ---

if !(IsPostBack)
{
 this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
}

 

--- .aspx of popup form ---

<script language="javascript">
        function GetRowValue(val)
        {
            window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val; //hardcoded value used to minimize the code. ControlID can be passed as query string to the popup window
            window.close();
        }
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px" AllowPaging="True">
            <Columns>
                <asp:TemplateField>
                    <AlternatingItemTemplate>
                        <asp:Button ID="btnSelect" runat="server" Text="Select" />
                    </AlternatingItemTemplate>
                    <ItemTemplate>
                        <asp:Button ID="btnSelect" runat="server" Text="Select" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

--- .vb file if vb.net is the language ---

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            DirectCast(e.Row.FindControl("btnSelect"), Button).Attributes.Add("onclick", "javascript:GetRowValue('" & e.Row.Cells(1).Text & "')") 'assuming that the required value column is the second column in gridview
        End If
    End Sub

--- .cs file if C#.net is the language ---

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
        ((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells(1).Text + "')");
        //assuming that the required value column is the second column in gridview
    }
}

 

I hope the code above is straight forward and easy to understand.

Happy Coding!!!

51 Comments

  • Nice code..
    but i altered a bit to get it runs on my visual web dev 2008...
    thx anyway

    --- .cs of parent.aspx if C#.net is the language ---

    if (!(IsPostBack))

  • Thanks dude, that's what i been searching for

  • I can't get it done....it shows a error that e.row is not declared....how am i suppose to solve this


    Thanks

  • This code is very nice,

  • error in ('" + e.Row.Cells(1).Text + "')"); if I change to ('" + e.Row.Cells[1].Text + "')");
    nothing error but I can't send the value to parent.

  • I can't send the value to parent.

  • hi...I got error in here when i tried your code... I got error in here : javascript:GetRowValue('" + e.Row.Cells(1).Text + "')");
    Sorry...I'm still beginner in .NET...

  • hi the code does not work for me neither...

    no value is being passes to the parent from the popup window and the window doesnt close after clicking on the select button.. which shows that it does not enter the piece of code where the getrowval is being called..

    how to solve this issue?

  • sorry guys i was out since some time... for those like

    preethi, stdanny, ronaldovn and Bluekaizen what problem you guys are having... some error?

  • Hi,
    what preethi said GridView1_RowDataBound event is not firing thats why it is not passing value to parent page .when i am clicking on button select
    GridView1_RowDataBound should fire but it is not firing that event.

  • @Harminder

    What I believe that you and preethi are not mapping GridView1 with the RowDataBound event using Events window.

    Try placing GridView on your form like this



    Here I manually map OnRowDataBound event with the handler GridView1_RowDataBound

    I hope it will solve your problem.

  • i have already map it on page load this event is firing but on select button it is not



    i am not using sqldatasource but filling from database
    from datareader through loop

  • @Harminder

    Try placing your code as its difficult to find the cause of problem.

  • when the pop window is closed and control is returned to main page.
    The textboxes have updated values but the problem is when i tried to read those values by code it is showing me Null.
    please help

  • @ankurvermaaries

    I just check the application again and placed another button to write the value on the page of the TextBox that was filled by the popup and it worked fine. Also try placing your code.

  • @yatie

    Try to modify your code like this

    DirectCast(e.Row.FindControl("btnSelect"), Button).Attributes.Add("onclick", "javascript:GetRowValue('" & e.Row.Cells(1).Text & "','"& e.Row.Cells(2).Text & "')")


    and the signature of javascript function will look like this

    function GetRowValue(val1, val2)

    What this code will do?
    It will pass 2 parameters i.e. first and second column values of the GridView in the javascript function.

    Hope it will solve your problem.

  • farazsk11,

    tq for ur code...

    very simple and helpful...tq..

  • Thank you very very much for this very awesome post, very helpful to us...

  • I WANT TO PASS A VALUE FROM ONE FORM TO THE POPUP AND GET THE SAME VALUE FROM THE POPUP TO ANOTHER FROM.

    IF ANYBODY KNOW THE CODE IN VB. PLEASE EMAIL ME ON sels2005j@yahoo.com


  • @Joseph:

    You can pass the value as a QueryString to the popup like this

    window.open("popup.aspx?MyPopupValue=SOME_VALUE","List","scrollbars=no,resizable=no,width=400,height=280");

    in the popup windows's load event you can write

    IF Request.QueryString("MyPopupValue") IsNot Nothing Then
    Dim strValue as String = Request.QueryString("MyPopupValue").ToString()
    'Rest of your code for using the value you received.
    End IF

  • farazsk, i used your code in my website and i get 2 different result..
    1-firefox is working fine
    2-i.explorer doesnt close the popup and return my values

    how can we modifiy the jscript codes to work with bot firefox and i.explorer??

  • @amanbre:

    When I wrote the code I tested it only with IE so I guess it should work with IE. Please check if it gives any javascript error.

  • i found the error and it is not about yor code..thx for returning

  • Hi, Faraz,
    Can you do the same thing using C# please.
    Ta

  • @TRaj:

    the code includes C# implementation as well.

  • i worked with this subject and every thing is worked fine but when i pass value and store is in textbox and then prerender page the value being null

  • @hani:

    I guess in prerender event ViewState of a control is not written or updated and since we were setting the value using javascript probably this could be the reason. Any way try to get it on Load event if it works then this should be the problem of ViewState as controls retain their values using ViewState.

  • Its perfectely running. if you not running properly add attribute of onRowdatabound="Function name". and change the textbox name of the script function in pop up pages

  • I have a popup with listview. One of the items on it I made a linkbutton. I did as explained in the article. I call the function in listview1_itemcommand instead of GridView1_RowDataBound
    The problem is that the user needs to click twice on that linkbutton. First time the page posts back and only second click does the job and returns value to the main window and popup closes.

    Why does not it work on first click?
    I spent 2 days on it, please help me.

  • I am sorry it is DataList control(not listview) that I am working with in popup. So it is DataList_ItemCommand where I call the function.

  • @ Ann:

    use DataList_ItemDatabound event. Try to write this in ItemDatabound event

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
    ((LinkButton)e.Item.FindControl("LinkButtonID")).Attributes.Add(("onclick", "javascript:GetRowValue('" + ((Label)e.Item.FindControl("lbID")).Text + "')");
    }

    Replace LinkButtonID with the actual LinkButtonID in the DataList. Here I assume that lbID is a label you are using to display IDs in the DataList.

    Hope it will solve your problem now.

  • farazsk11

    Thank you so much, it works!

  • excuse me
    I tested your first & second examples
    in first example(Feb 16 2008) you have a master page in your parent page(like me)
    but in second example(July 23 2008) you don't use master page

    second example work very well but with masterpage,the popup window dosen't close and don't pass values to parent page.

    please help me and say me what can I do?
    I have 2 pages that are derived from MasterPage(like first example)
    how must i write my code to pass values & close pop up page?

  • Awesome code, thats working perfectly.

  • Thanks. This code is perfect, I modified as per my requirement and implemented.

  • I'm going to try the code again, but please next time try to present a full solution (it will be great if attached), because most of us are beginners. Thanks anyway.

  • Wow, this help me so much. Thank you, thank you

  • Hi,

    I am using ASP.net2.0. I am having Parent page(which is Master page implemented) and Popup Page. Also i am having 10 columns in SQL server(Say col1,col2,col3,...col10). In my parent page i having 10 textboxes for each value.

    Now my problem is, I want show the Col2,col3, col4 and col7 in Popup. When i select any row of columns in the popup window, all the values (which are not shown ) should also bind with the controls in Parent tables..How to do this using Javascript

    Note:

    1)I know how to Open Popup using Javascript.

    2)I know how to bind all the value when displaying all the columns values in Popup.

    TIA

  • can anyone say me how to get the values of selected rows in datagrid to a window form?

  • farazsk11 -

    Great code. Would it be possible to see it in VB?

    Thanks!

  • @mwulfe:

    Hi,

    Please check the sample code in the blog and look for the following line:

    --- .vb file if vb.net is the language ---

    You will find the implementation in VB.

  • nice code...

    would you give also example using c# form...

  • @Kenn:

    Hi, C# example is there in the blog. Incase if you couldn't find it, let me paste it here as well.

    protected void Page_Load(object sender, EventArgs e)
    {
    if !(IsPostBack)
    {
    this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
    }
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
    ((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells(1).Text + "')");
    //assuming that the required value column is the second column in gridview
    }
    }


  • Thanks Faraz , for ur valuable code.

  • hi Faraz,

    if I have a gridview defined like this



    <asp:LinkButton ID="UploadCompleteLinkButton" runat="server" CommandName="UploadComplete" Text="Upload complete" CommandArgument='' OnClick="btnPopup_Click">







    Confirmation




    Are you complete uploading trace file(s) to the server?


    Id is:
    <asp:Label ID="popupIdLabel" runat="server" Text='' >










    The popupIdLabel.Text shows a valid CustomerId, how can I pass this value to ConfirmExecution_Click in code behind so I could grab the CustomerId to update the database?

    thanks.

  • How To Pass Value from User Web Control to Parent ASPX Page

  • Hey thanks I have also done my logic based

  • Passing value from popup window to parent form s textbox.. Great! :)

  • Thanks for this great article. You saved my hours of effort.

  • gud day,
    I tried your code but i encountered an error:
    Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

    i already tried to insert this : into may page directive but the error still occurs.

    hope you can help me...

  • I don't know where I'm going wrong.
    This is what I have - On parent page, I have plain textbox to enter zipcode on a contentpage inside the contentplaceholder. When user clicks on Find My School the web app looks up schools in that area. I am able to open a new window that show these school options to the user to select from in a listbox. The value selected by user in listbox in this child window needs to be passed back to the parent page and displayed in the textbox txtHighSchool.

    Thank you.

    I tried the exact thing you have. Please see below. I am disappointed why this may not be working. Your help will be very much appreciated.









Comments have been disabled for this content.