filling parent form from child form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • malli kai
    New Member
    • Sep 2011
    • 6

    filling parent form from child form

    Hi!

    I created one parent webform with so many fields and one popup window(child form) with a GridView.

    I want to fill the parent form with selected data in the GridView.

    To do this, in parent window I have the following code:
    Code:
    <script type="text/javascript">
      function GetValues()
      {
        window.open('search patient.aspx');
        return false;
      }
    </script>
    In child form I have this code:
    Code:
    <script type="text/javascript">
      var lastRowSelected;
      var originalColor;
    
      function GridView1_selectRow(row, Pat_Id)
      {
        if (lastRowSelected != row)
        {
          if (lastRowSelected != null)
          {
            lastRowSelected.style.backgroundColor = originalColor;
            lastRowSelected.style.color = 'Black'
            lastRowSelected.style.fontWeight = 'normal';
          }
          originalColor = row.style.backgroundColor
          row.style.backgroundColor = 'BLUE'
          row.style.color = 'White'
          row.style.fontWeight = 'normal'
          lastRowSelected = row;
        }
      }
    
      function GridView1_mouseHover(row)
      {
        row.style.cursor = 'hand';
      }
      function setRowNo(rowNo)
      {
        document.getElementById('hidRowNo').value = rowNo;
      }
        
      function returnValues()
      {
        if(document.getElementById('hidRowNo').value != "")
        {
          var rowNo = document.getElementById('hidRowNo').value;
          var grd = document.getElementById('GridView1');
          //alert(grd.rows[rowNo].cells[0]);
          //alert(grd.rows[rowNo].cells[1]);
          window.opener.document.getElementById('patidtextbox').value = grd.rows[rowNo].cells[0].innerhtml;
                window.opener.document.getElementById('nametextbox').value = grd.rows[rowNo].cells[1].innerhtml;
          window.close();
        }
        else
        {
          alert('Select any row from grid');
        }
      }
    </script>
    In GridvView_RowDa taBound I have:
    Code:
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        e.Row.ID = e.Row.Cells[0].Text;
        e.Row.Attributes.Add("onclick", "GridView1_selectRow(this,'" + e.Row.Cells[0].Text + "')+setRowNo(" + (e.Row.RowIndex + 1) + ")");
        //e.Row.Attributes.Add("onclick1", "setRowNo(" + (e.Row.RowIndex + 1) + ");");
        e.Row.Attributes.Add("onmouseover", "GridView1_mouseHover(this)");
      }
    }
    When I execute this no error is occurs and no data is retrieved.

    Please any one help me.
    Please send me correct code for this and please tell me the wrong in my code.

    please anyone help me.........

    thanks in advance...
    Last edited by Frinavale; Nov 1 '11, 01:26 PM. Reason: Added code tags, formatted code so that it is easier to read and corrected grammar.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    The solution to your problem requires the use of JavaScript (client-side scripting) and server side coding to work properly.

    I created a small demonstration application to help explain what you need to do.

    Since I don't have a database in this application, I have created a Person class. It has an ID property, a FirstName property, a MiddleName property, and LastName property. It also has a property called DisplayInParent JS. I use it for binding purposes when I'm displaying the Person in the GridView. It returns a string that contains the JavaScript to call when the user is selected.

    This is my person class:
    Code:
    public class Person
    {
    
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        private int _id;
        public int ID
        {
            get { return _id; }
            set { throw new Exception("This property is read only."); }
        }
        public string DisplayInParentJS
        {
            get { return String.Format("{0}{1}{2}", "javascript:DisplayInParentWindow(", ID.ToString(), ");"); }
            set { throw new Exception("This property is read only."); }
        }
    
        public Person(int id, string firstName, string middleName, string lastName)
        {
            _id = id;
            this.FirstName = firstName;
            this.MiddleName = middleName;
            this.LastName = lastName;
        }
    }
    I have 2 forms in my application: WebForm1.aspx and WebForm2.aspx.

    WebForm1 is the parent window.

    It contains controls for displaying the selected person, a button that opens the child window (WebForm2), a HiddenField and a LinkButton which the user cannot see.

    It also contains a JavaScript method called DisplayPersonDe tails which takes 1 parameter: the ID of the selected person. This method sets the value of the HiddenField to the ID of the selected person and triggers the Click event for the LinkButton (that is hidden on the page).

    In order to trigger the Click event for the LinkButton I am using the JavaScript method __doPostBack() which is automatically generated by ASP.NET for this purpose. The first parameter in the __doPostBack() is the ID of the control that is causing the event. So, I am passing the ClientID property of the LinkButton to the __doPostBack() method so that a server-side Click event is generated for the LinkButton upon posting back to the server.

    Here is my page code for WebForm1
    Code:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
    
    <!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></title>
        <style type="text/css">
            .label
            {
                color: #666666;
                display: block;
                float: left;
                width: 150px;
            }
            
            h1
            {
                font-size: 2em;
                color: #5D7B9D;
                text-align: center;
                margin: 0;
            }
            .personDetailsSection
            {
                border: 1px solid #5D7B9D;
                padding: 10px;
            }
            .content
            {
                width: 21em;
                margin: 0px auto;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div class="content">
            <h1>
                Person Details</h1>
            <div class="personDetailsSection">
                <div>
                    <div class="label">
                        <asp:Label ID="PersonIDPrompt" Text="ID" runat="server" CssClass="label" />
                    </div>
                    <asp:TextBox ID="PersonID" runat="server" ReadOnly="true" Enabled="false" />
                </div>
                <div>
                    <div class="label">
                        <asp:Label ID="PersonFirstNamePrompt" Text="First Name" runat="server" CssClass="label" />
                    </div>
                    <asp:TextBox ID="PersonFirstName" runat="server"></asp:TextBox>
                </div>
                <div>
                    <div class="label">
                        <asp:Label ID="PersonMiddleNamePrompt" Text="Middle Name" runat="server" CssClass="label" />
                    </div>
                    <asp:TextBox ID="PersonMiddleName" runat="server"></asp:TextBox>
                </div>
                <div>
                    <div class="label">
                        <asp:Label ID="PersonLastNamePrompt" Text="Last Name" runat="server" CssClass="label" />
                    </div>
                    <asp:TextBox ID="PersonLastName" runat="server"></asp:TextBox>
                </div>
                <div style="text-align:center; margin:1em 0 0 0;">
                    <asp:Button ID="OpenChildWindow" runat="server" Text="Display Existing Options" OnClientClick="window.open('WebForm2.aspx', 'ChildWindow','toolbar=no,menubar=no,resizable=yes'); return false" />
                </div>
                <asp:LinkButton ID="DisplaySelectedPerson" runat="server" Text="Display Selected Person"
                    Style="display: none;" />
                <asp:HiddenField ID="SelectedPersonID" runat="server" />
                <script type="text/javascript">
                    function DisplayPersonDetails(id) {
                        var hiddenField = document.getElementById('<%=SelectedPersonID.ClientID %>');
                        hiddenField.value = id;
                        __doPostBack('<%=DisplaySelectedPerson.ClientID %>', '');
                    }
                </script>
            </div>
        </div>
        </form>
    </body>
    </html>
    In my C# code for WebForm1 I am handling the LinkButton's Click event...where I am retrieving the ID of the selected person from the HiddenField in order to retrieve the selected person from Session so that I can display their details in the page.

    Here is my C# code for WebForm1:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                DisplaySelectedPerson.Click+=new EventHandler(DisplaySelectedPerson_Click);
            }
    
            void DisplaySelectedPerson_Click(object sender, EventArgs e)
            {
                List<Person> people = (List<Person>)Session["people"];
                if (people != null)
                {   
                    int personID;
                    int.TryParse(SelectedPersonID.Value, out personID);
                    Person selectedPerson = people.Find((existingPerson) => existingPerson.ID == personID);
                    if (selectedPerson != null)
                    {
                        PersonID.Text = selectedPerson.ID.ToString();
                        PersonFirstName.Text = selectedPerson.FirstName;
                        PersonMiddleName.Text = selectedPerson.MiddleName;
                        PersonLastName.Text = selectedPerson.LastName;
    
                    }
                }
            }
        }
    }

    In WebForm2, I have implemented a JavaScript method called DisplayInParent Window. This method takes 1 parameter: the ID of the selected person. It uses the JavaScript window.opener method to call the DisplayPersonDe tails JavaScript method that exists in the parent window (WebForm1).

    In WebForm2, I have a GridView that is displaying all of the people in the system. It has columns that are bound to the person's FirstName property, MiddleName proeprty, and LastName property. It also has a TemplateField column that has a HyperLink that is bound to the person's DisplayInParent JS property. When the user clicks the HyperLink, the DisplayInParent Window JavaScript method will be called with the selected person's ID.

    Here is my WebForm2 code:
    Code:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>
    
    <!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></title>
        <style type="text/css">
            .label
            {
                color: #666666;
                display: block;
                float: left;
                width: 150px;
            }
            
            h1
            {
                font-size: 2em;
                color: #5D7B9D;
                text-align: center;
                margin: 0;
            }
            .personDetailsSection
            {
                border: 1px solid #5D7B9D;
                padding: 10px;
            }
            .content
            {
                width: 21em;
                margin: 0px auto;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <script type="text/javascript">
    
            function DisplayInParentWindow(id) {
    
                window.opener.DisplayPersonDetails(id);
            }
        </script>
        <div class="content">
            <h1>
                People in the System</h1>
            <div class="personDetailsSection">
                <asp:GridView ID="PeopleInfo" runat="server" AutoGenerateColumns="false" CellPadding="4"
                    ForeColor="#333333" GridLines="None">
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                    <Columns>
                        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                        <asp:BoundField DataField="MiddleName" HeaderText="Middle Name" />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <a href='<%#Eval("DisplayInParentJS") %>'>Select</a>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </div>
        </form>
    </body>
    </html>
    In the C# code for WebForm2 I am simply generating a list of people and storing it in Session if one doesn't already exist. If a list of people already exists, I am simply retrieving this list from Session. All I do is set the DataSource for the GridView to the list of people and bind the GridView to the list.

    Here is my C# code for WebForm2:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class WebForm2 : System.Web.UI.Page
        {
            private string[] firstNames = { "Sneezy", "Sleepy", "Dopey", "Doc", "Happy", "Bashful", "Grumpy" };
            private string[] middleNames = { "Blick", "Flick", "Glick", "Snick", "Plick", "Whick", "Quee" };
            private string[] lastNames = { "Dwarf1", "Dwarf2", "Dwarf3", "Dwarf4", "Dwarf5", "Dwarf6", "Dwarf7" };
            private List<Person> _people;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Session["people"] == null)
                {
                    _people = new List<Person>();
                    for (int i = 0; i < firstNames.Length; i++)
                    {
                        _people.Add(new Person(i,firstNames[i], middleNames[i], lastNames[i]));
                    }
                    Session["people"] = _people;
                }
                else
                {
                    _people = (List<Person>)Session["people"];
                }
    
            }
    
            void Page_PreRender(object sender, EventArgs e)
            {
                PeopleInfo.DataSource = _people;
                PeopleInfo.DataBind();
            }
    }
    I think this is pretty straightforwad, but here's a recap of what is going on.

    I have a JavaScript method in WebForm1 (the parent window) that sets the value for a HiddenField to the ID of the selected person (which is passed into the method as a parameter) and calls the __doPostBack() method in order to trigger a server-side Click event for a hidden LinkButton on the page.

    I have a JavaScript method in WebForm2 (the child window) which takes 1 argument: the ID of the selected person. It uses the JavaScript window.opener property to call the JavaScript method in WebForm1 (the parent window) that I have just described.

    There's nothing really fancy about this...but it does take a bit of thought to accomplish.

    I have attached the working sample application (created in Visual Studio 2010).

    -Frinny
    Attached Files
    Last edited by Frinavale; Nov 2 '11, 06:33 PM.

    Comment

    • malli kai
      New Member
      • Sep 2011
      • 6

      #3
      filling parent form

      Hi Frinavale.

      Thank u for helping me.

      Now I have a question.

      I have two forms one form(parent form) another form(child form).

      In parent form I have a number of fields.

      In child form I have a GridView.

      By using this GridView id column I filled the idtextbox in the parent form.

      I take one public variable in child form and the id is append to this variable.now i used this variable in parent form.

      Is this correct or not?

      Another question I have is...

      I use this public variable in parent form.
      By using this variable:
      Code:
      int id=request.querystring["<id which value getting from the gridview>"];
      I know how to get the data from the database by using this id.

      For example:
      Code:
      select * from "tablename" where id="<variable>"
      I write this code in page load event in parent form then this code executes when the page first loads.

      But I want load this code to parent form when the child form is close.

      Now in which place in parent form do I write this code?

      Do you understand this?
      I think it is clear.
      Please help me.

      Thanks in advance.

      please help me with in one day...please
      Last edited by Frinavale; Nov 4 '11, 02:48 PM. Reason: Corrected grammar and spelling errors

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        I take one public variable in child form and the id is append to this variable.now i used this variable in parent form.

        Is this correct or not?

        ...
        Are you actually using web forms or have you created a UserControl?

        Essentially, you cannot access the public properties or members of WebForm2 from WebForm1 because of how web pages work.

        When a web browser requests a page, the web server forwards the request to ASP.NET. ASP.NET creates the page and all of the server-side objects that are required to process the request. After everything has been processed, HTML is generated so that the browser can display the results. This HTML is sent to the browser and then everything on the server is destroyed.

        So, when you see the WebForm1 page in the browser, nothing for that page exists on the server.

        Likewise, when you see WebForm2 in the browser, nothing for that page exists on the server.

        What I'm getting at is that you cannot do something like this:
        Code:
        String result = webForm2.somePublicProperty;
        Because WebForm2 doesn't exist.

        This is why you use the query string, or cookies...or in my example a combination of JavaScript and HiddenFields to pass the information to WebForm1 about WebForm2.




        I use this public variable in parent form.

        By using this variable:

        Code:
        int id = request.querystring["<id which value getting from the gridview>"];
        I know how to get the data from the database by using this id.[/quote]


        Now I am really confused...you' re using the Query String in this code but how does this relate to a public field?

        I'm just going to ignore this for now...

        Code:
        select * from "tablename" where id="<variable>"
        i write this code in page load event in parent form then this code executes when the page first loads...
        but i want load this code to parent form when the child form is close....
        Ok, I'm going to modify the application that I previously posted to show you how to do this.

        -Frinny

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          There are a couple of ways to populate the fields in the Parent forum once the child window is closed.

          One way would be to use the JavaScript OnBeforeUnload event...
          But not all browsers support this event (Opera doesn't)

          So, to get around this I closed the child window from the JavaScript that updates the GridView in the parent window.

          Like this:
          (WebForm1 modified code)
          Code:
          <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
          
          <!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></title>
              <style type="text/css">
                  .label
                  {
                      color: #666666;
                      display: block;
                      float: left;
                      width: 150px;
                  }
                  
                  h1
                  {
                      font-size: 2em;
                      color: #5D7B9D;
                      text-align: center;
                      margin: 0;
                  }
                  .personDetailsSection
                  {
                      border: 1px solid #5D7B9D;
                      padding: 10px;
                  }
                  .content
                  {
                      width: 21em;
                      margin: 0px auto;
                  }
              </style>
          </head>
          <body>
              <form id="form1" runat="server">
              <div class="content">
                  <h1>
                      Person Details</h1>
                  <div class="personDetailsSection">
                      <div>
                          <div class="label">
                              <asp:Label ID="PersonIDPrompt" Text="ID" runat="server" CssClass="label" />
                          </div>
                          <asp:TextBox ID="PersonID" runat="server" ReadOnly="true" Enabled="false" />
                      </div>
                      <div>
                          <div class="label">
                              <asp:Label ID="PersonFirstNamePrompt" Text="First Name" runat="server" CssClass="label" />
                          </div>
                          <asp:TextBox ID="PersonFirstName" runat="server"></asp:TextBox>
                      </div>
                      <div>
                          <div class="label">
                              <asp:Label ID="PersonMiddleNamePrompt" Text="Middle Name" runat="server" CssClass="label" />
                          </div>
                          <asp:TextBox ID="PersonMiddleName" runat="server"></asp:TextBox>
                      </div>
                      <div>
                          <div class="label">
                              <asp:Label ID="PersonLastNamePrompt" Text="Last Name" runat="server" CssClass="label" />
                          </div>
                          <asp:TextBox ID="PersonLastName" runat="server"></asp:TextBox>
                      </div>
                      <div style="text-align:center; margin:1em 0 0 0;">
                         <asp:Button ID="OpenChildWindow" runat="server" Text="Display Existing Options" OnClientClick="childWindow = window.open('WebForm2.aspx', 'ChildWindow', 'toolbar=no,menubar=no,resizable=yes'); return false;" />
                         
                      </div>
                      <asp:LinkButton ID="DisplaySelectedPerson" runat="server" Text="Display Selected Person"
                          Style="display: none;" />
                      <asp:HiddenField ID="SelectedPersonID" runat="server" />
                      <script type="text/javascript">
                          var childWindow;
                          function DisplayPersonDetails(id) {
                              var hiddenField = document.getElementById('<%=SelectedPersonID.ClientID %>');
                              hiddenField.value = id;
                              if (childWindow) {
                                  childWindow.close();
                              }
                              __doPostBack('<%=DisplaySelectedPerson.ClientID %>', '');
                          }
                      </script>
                  </div>
              </div>
              </form>
          </body>
          </html>
          Now to answer your question about where you should put the code that retrieves data from the database....

          This really does depend on how you are posting back to the server with the ID that you need to retrieve data about.

          In my example application, you would put the code to retrieve the data from the database in the LinkButton's Click event because a Click Event is generated when I used the JavaScript __doPostback() method to post back to the server.

          If you aren't using this method to post back to the server, then I think that you'll have to do it in your page load...because no other server-side event will be created that you can handle in your C# code.

          It would be a lot easier if we had a code reference from your code to talk about.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            I have a feeling that you would be better off using a UserControl instead of a Form to display the GridView.

            The UserControl would be Part of the WebForm1 page.
            That way your WebForm1 page can access the public properties of the User control so that it can update itself...it can also handle any events that the UserControl generates.

            In your case, the UserControl with the GridView that has the options in it would be hidden on the page until the user clicked the button to select from it.

            The UserControl would then be displayed on the Page...on top of the content of the page...but not in a popup window.

            The user would then make their selection and hit a close button.
            The close button would post back to the server....at which time the UserControl would be hidden and an Event would be raised to notify the WebForm1 page that a choice has been made.

            WebForm1 would handle the event that the UserControl raised...and would display the details about the choice in the GridView.

            I modified the demonstration application to show you how to use UserControls instead of Web Forms.

            The first thing I did was create a new page (web form) called "ParentWebForm. aspx". I copied the controls that were used previously to display the Person's details into this page.

            I then added a UserControl to the page called "ChoicesChild.a scx" to the project. I then copied the controls used previously to display the Person Choices (a GridView with people) into the UserControl.

            I built the project and then added the ChildChoices user control to the ParentWebForm.

            Here is my ParentWebForm:
            Code:
            <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ParentWebForm.aspx.cs" Inherits="WebApplication1.ParentWebForm" %>
            
            <%@ Register Src="ChoicesChild.ascx" TagName="ChoicesChild" TagPrefix="uc1" %>
            <!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></title>
                <style type="text/css">
                    .label
                    {
                        color: #666666;
                        display: block;
                        float: left;
                        width: 150px;
                    }
                    
                    h1
                    {
                        font-size: 2em;
                        color: #5D7B9D;
                        text-align: center;
                        margin: 0;
                    }
                    .personDetailsSection
                    {
                        border: 1px solid #5D7B9D;
                        padding: 10px;
                    }
                    .content
                    {
                        width: 21em;
                        margin: 0px auto;
                    }
                </style>
            </head>
            <body>
                <form id="form1" runat="server">
                <div class="content">
                    <h1>
                        Person Details</h1>
                    <div class="personDetailsSection">
                        <div>
                            <div class="label">
                                <asp:Label ID="PersonIDPrompt" Text="ID" runat="server" CssClass="label" />
                            </div>
                            <asp:TextBox ID="PersonID" runat="server" ReadOnly="true" Enabled="false" />
                        </div>
                        <div>
                            <div class="label">
                                <asp:Label ID="PersonFirstNamePrompt" Text="First Name" runat="server" CssClass="label" />
                            </div>
                            <asp:TextBox ID="PersonFirstName" runat="server"></asp:TextBox>
                        </div>
                        <div>
                            <div class="label">
                                <asp:Label ID="PersonMiddleNamePrompt" Text="Middle Name" runat="server" CssClass="label" />
                            </div>
                            <asp:TextBox ID="PersonMiddleName" runat="server"></asp:TextBox>
                        </div>
                        <div>
                            <div class="label">
                                <asp:Label ID="PersonLastNamePrompt" Text="Last Name" runat="server" CssClass="label" />
                            </div>
                            <asp:TextBox ID="PersonLastName" runat="server"></asp:TextBox>
                        </div>
                        <div style="text-align: center; margin: 1em 0 0 0;">
                            <asp:Button ID="OpenChildWindow" runat="server" Text="Display Existing Options" OnClick="OpenChildWindow_Click" />
                            <uc1:ChoicesChild ID="ChoicesChildUserControl" runat="server" Visible="False" />
                        </div>
                    </div>
                </div>
                </form>
            </body>
            </html>
            Notice that I have set the ChildChoices user control to have Visible="false" . This means that the user control will not be rendered in HTML...so it will not be displayed to the user.

            The OpenChildWindow button no longer calls any JavaScript. Instead I handle the server-side click event for the button in my C# code. In that code I set ChildChoices Visible property to True.

            Here is the C# code for the ParentWebForm page:
            Code:
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using System.Web.UI;
            using System.Web.UI.WebControls;
            
            namespace WebApplication1
            {
                public partial class ParentWebForm : System.Web.UI.Page
                {
                    protected void Page_Load(object sender, EventArgs e)
                    {
                        ChoicesChildUserControl.Closed += new EventHandler(ChoicesChildUserControl_Closed);
                    }
            
                    void ChoicesChildUserControl_Closed(object sender, EventArgs e)
                    {
                      
                        Person selectedPerson = ChoicesChildUserControl.SelectedPerson;
                        if (selectedPerson != null)
                        {
                            PersonID.Text = selectedPerson.ID.ToString();
                            PersonFirstName.Text = selectedPerson.FirstName;
                            PersonMiddleName.Text = selectedPerson.MiddleName;
                            PersonLastName.Text = selectedPerson.LastName;
            
                        }
                    }
            
                    protected void OpenChildWindow_Click(object sender, EventArgs e)
                    {
                        ChoicesChildUserControl.Visible = true;
                    }
                }
            }
            Notice how I am handling the Close event for the ChildChoices user control?

            Normally user controls do not have a Close event.
            I added this custom event to the ChildChoices user control.

            Here is the code I have for my ChildChoices user control:
            Code:
            <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ChoicesChild.ascx.cs"
                Inherits="WebApplication1.ChoicesChild" %>
            <div id="pageBlocker" style="height:100%; width:100%; background-color: black; position:absolute; top:0; left:0; z-index:1; opacity: 0.4; filter: alpha(opacity=40);">
            </div>
            <div id="choiceContent" class="content" style="position:absolute; top:0; left:0; z-index:2; border:1px solid #5D7B9D; background-color:White;">
                <h1>People in the System</h1>
                <div class="personDetailsSection">
                    <asp:GridView ID="PeopleInfo" runat="server" AutoGenerateColumns="false" CellPadding="4"
                        AutoGenerateSelectButton="true" ForeColor="#333333" GridLines="None">
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                        <Columns>
                            <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                            <asp:BoundField DataField="MiddleName" HeaderText="Middle Name" />
                            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                            <asp:TemplateField ShowHeader="false" >
                                    <ItemTemplate>
                                        <asp:Label ID="personID" runat="server" Text='<%#Eval("ID") %>' style="display:none" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                    <asp:Button ID="closeButton" runat="server" Text="Close" 
                        onclick="closeButton_Click" />
                </div>
            </div>
            <script type="text/javascript">
                var choiceContent = document.getElementById('choiceContent');
            
                var windowWidth;
                if (window.innerWidth) {
                    windowWidth = window.innerWidth;
                } else if (document.documentElement && document.documentElement.clientWidth) {
                    windowWidth = document.documentElement.clientWidth;
                } else if (document.body) {
                    windowWidth = document.body.clientWidth;
                }
            
                var choiceContentWidth = choiceContent.offsetWidth ? choiceContent.offsetWidth : choiceContent.clientWidth;
                var leftOffset = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
                leftOffset = leftOffset / 2;
                var left = (windowWidth / 2 - choiceContentWidth / 2) + leftOffset;
                choiceContent.style.left = left + "px";
            
            </script>
            And here is the C# code for the ChoicesChild user control:
            Code:
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using System.Web.UI;
            using System.Web.UI.WebControls;
            
            namespace WebApplication1
            {
                public partial class ChoicesChild : System.Web.UI.UserControl
                {
                    public event EventHandler Closed;
                    public Person SelectedPerson { get; set; }
            
                    private List<Person> _people;
            
                    protected void Page_Load(object sender, EventArgs e)
                    {
                        if (Session["people"] == null)
                        {
                            string[] firstNames = { "Sneezy", "Sleepy", "Dopey", "Doc", "Happy", "Bashful", "Grumpy" };
                            string[] middleNames = { "Blick", "Flick", "Glick", "Snick", "Plick", "Whick", "Quee" };
                            string[] lastNames = { "Dwarf1", "Dwarf2", "Dwarf3", "Dwarf4", "Dwarf5", "Dwarf6", "Dwarf7" };
                            List<Person> _people;
                            _people = new List<Person>();
                            for (int i = 0; i < firstNames.Length; i++)
                            {
                                _people.Add(new Person(i, firstNames[i], middleNames[i], lastNames[i]));
                            }
                            Session["people"] = _people;
                        }
                        else
                        {
                            _people = (List<Person>)Session["people"];
                        }
            
                    }
            
                    void Page_PreRender(object sender, EventArgs e)
                    {
                        PeopleInfo.DataSource = _people;
                        PeopleInfo.DataBind();
                    }
            
                    protected void closeButton_Click(object sender, EventArgs e)
                    {
                        int personID;
                        Label personIDLabel = (Label)PeopleInfo.SelectedRow.FindControl("personID");
                        int.TryParse(personIDLabel.Text,out personID);
                         this.SelectedPerson = _people.Find((existingPerson) => existingPerson.ID == personID);
                        Closed(this,new EventArgs());
                        this.Visible = false;
                    }
                }
            }
            In this C# code I handle the closeButton's click event. In that event I retrieve the selected person and set the SelectedPerson property with the information that I've retrieved...and then I raise the custom Close event for the user control.

            In the ParentWebForm I handle the Close event and retrieve the selected person using the SelectedPerson property of the ChoicesChild user control.

            I didn't have to do it this way though.
            I could have added a "SelectedPerson ID" property to the ChoicesUser control...and set that value instead. Then back in the ParentWebForm page, I could have retrieved the ID of the person to use to retrieve data from a database about the person.


            I have attached a project with the working demonstration code (again it's a Visual Studio 2010 project)


            -Frinny
            Attached Files
            Last edited by Frinavale; Nov 4 '11, 04:50 PM.

            Comment

            Working...