locked
Hiding and showing forms in C# RRS feed

  • Question

  •  Hi all!

    Here is a (another) noob question from me :(

    This is what I intend to do:

    I have a button in my main form; the button click event causes the main form to hide and open up a new form. When I close this new form I want the main form to reappear.

    I have this piece of code in the button click event in main from:

    private void button1_Click(object sender, EventArgs e
    {
      Form2 dataForm = new Form2(comboBox1.Text);
      dataForm.TopLevel = false;
      dataForm.Parent = this;
      dataForm.Show();
      this.Hide();
    }
    

    In the child form closing event I have:

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
      this.ParentForm.Show();
    }
    

    But when I click the button it hides the main window, but the child window never opens. The program is still running. What is wrong?

    Also, I added the dataForm.TopLevel = false; line to avoid an exception which occurred during run time which said - "Top-level control cannot be added to a control". Adding that line avoided the exception, but I haven't really understood what has caused the exception. Could anybody explain this too please?

    Thanks!

    Monday, December 13, 2010 10:02 PM

Answers

  • There is no way to know what your Form2 constructor is, what your Form2.ParentForm is or how you got the code you posted to compile.  This code works normally:

        private void button1_Click(object sender, EventArgs e)
        {
          
    Form frm2 = new Form();
          frm2.Show();
          
    this.Hide();
          frm2.FormClosing += Frm2_Closing; 
        }
        
    private void Frm2_Closing(object sender, FormClosingEventArgs e)
        {
          
    this.Show();
        }

    • Proposed as answer by Rudedog2 Tuesday, December 14, 2010 12:46 AM
    • Marked as answer by surdiv Wednesday, December 15, 2010 8:39 PM
    Monday, December 13, 2010 10:22 PM

All replies

  • There is no way to know what your Form2 constructor is, what your Form2.ParentForm is or how you got the code you posted to compile.  This code works normally:

        private void button1_Click(object sender, EventArgs e)
        {
          
    Form frm2 = new Form();
          frm2.Show();
          
    this.Hide();
          frm2.FormClosing += Frm2_Closing; 
        }
        
    private void Frm2_Closing(object sender, FormClosingEventArgs e)
        {
          
    this.Show();
        }

    • Proposed as answer by Rudedog2 Tuesday, December 14, 2010 12:46 AM
    • Marked as answer by surdiv Wednesday, December 15, 2010 8:39 PM
    Monday, December 13, 2010 10:22 PM
  • Hello John,

    Thanks for the code. But, I think I should explain a bit more about my issue.

    First of all I am a total newbie to C#. I am trying to write code by going through forums and on-line tutorials. 

    What I had done in my project is - 

    (i) I first added a form(Form1) with a button and a combo box.

    (ii) I connected the northwind database and set the combo box so that it will display contact names in its drop down list.

    (iii) I added a second form(Form2) to the project and added datagrid view to it.

    I was looking to select a contact name from the combo box in Form1 and then on clicking the button in that form, the second form will open which will display all the order details of that particular customer in datagrid view. 

    My Form2 constructor look like this:

    public Form2(string contactName)
        {
          string customerID;
          InitializeComponent();
          bindingNavigator1.Enabled = true;
          SqlConnection mySqlConn = new SqlConnection("Data Source=.;" + "AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL10.MSSQLSERVER\\MSSQL\\DATA\\northwnd.mdf;" + "Integrated Security=True;" + "Persist Security Info=True;" + "User ID=sa;" + "Password=password1;" + "Connect Timeout=30;" + "User Instance=True;");
          mySqlConn.Open();
    .
          using (SqlCommand command = new SqlCommand("select CustomerID from Customers where ContactName = '" + contactName + "'", mySqlConn))
          {
            using (SqlDataReader reader = command.ExecuteReader())
            {
              reader.Read();
              customerID = reader.GetString(0);
            }
    
            using (SqlDataAdapter command1 = new SqlDataAdapter("select * from Orders where CustomerID = '" + customerID + "'", mySqlConn))
            {
              DataTable myDataTable = new DataTable();
              command1.Fill(myDataTable);
              dataGridView1.DataSource = myDataTable;
            }
          }
        }
    

    ..which is the missing piece from the code I have posted in my first post.

    As you can see, in the button click event, I created a instance of Form2 (which I guess is wrong!). I then did all the rest of the stuff in the code in the first post assuming that it would do what I want. 

    Your code opens a child form and hides the parent form; and it also opens the parent form when the child form is closed. But how will I add a datagrid view and other things which I might want to add? Is there no way to add it in the design view to a form and use it as the child form (like what I was trying to do)?

    I feel that my code is all wrong now. Please bare with me, I am a total newbie. Please help!

    Tuesday, December 14, 2010 9:05 PM
  • What problem do you have when you use the code I posted, but with your Form2?  What do you mean by parent and child form?  I don't see any MDI code.
    Tuesday, December 14, 2010 9:34 PM
  • What problem do you have when you use the code I posted, but with your Form2?  What do you mean by parent and child form?  I don't see any MDI code.


    That problem is solved.  I think there is a new question.

    Walkthrough: A Database Master-Detail Application 

    This link uses Northwinds database.  The main form is a DGV instead of a combobox.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://rudedog2.spaces.live.com/default.aspx

    Tuesday, December 14, 2010 10:34 PM
  • Hello John,

    I modified my code based on the code suggested by you as follows:

     

    private void button1_Click(object sender, EventArgs e)
      {
       Form2 dataForm = new Form2(comboBox1.Text);
       dataForm.Show();
       this.Hide();
       dataForm.FormClosing += dataForm.Form2_FormClosing;
      }
    

     

    I had to make the Form2_FormClosing function public to get the code to compile. Is this the right approach?

    Also, I have the Form2_FormClosing event like this:

     

    public void Form2_FormClosing(object sender, FormClosingEventArgs e)
      {
       this.Show();
      }
    

     

    This is the form closing event which I generated by double clicking on the events window for Form2.

    When I execute this code - dataForm window opened on the button click and the main form hide itself, which is what I wanted to do, but the main form did not show itself when I closed the dataForm window. How do I tell the code to show my main form again when I close the dataForm?

    In the this.show() in form2 closing event, this pointer is pointing to dataForm isn't it? So it has to be wrong anyway! :(

    You asked about the MDI code; there isn't any. That was me doing stupid things without knowing what I was doing. I have now removed the dataForm.parent = this statement from the code as you can see.

    @Rudedog2

    That was not a second question, I was still trying to explain my same issue, but I couldn't explain it well enough due to my lack of knowledge and I managed to confuse both of you!

    Wednesday, December 15, 2010 7:19 PM
  • Did you try that code out in a small test project?  It should not have been necessary to declare that method as public.  If so, then you are not using John's approach as he intended it to be used.

     

    Always , always use create a test project when you are testing new and unfamiliar code snippets.  Protect your the time that you have invested in your main application.  Avoid accidents and those single word, colorful metaphors.  Once you corrupt a project, it is usually difficult and frequently impossible to go back and restore it.

    Always create a test project.

    John's sample requires just a single form with a button on it, which needs to be connected to a Click event handler.  You can change the line that defines the dataform variable to be this.

    Form dataform = new Form();

    That should suffice for your test project.  This will allow you to observe the behavior of how forms can programmed to open and close one another.

    You may call me Rudy.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://rudedog2.spaces.live.com/default.aspx

    Wednesday, December 15, 2010 7:30 PM
  • To clarify futher:  My code subscribes to Form2's FormClosing event in Form1.  You're dancing around this,  adding handlers in Form2, where there should be none.

    Wednesday, December 15, 2010 8:30 PM
  • Hello Rudy!

    Thanks for your reply. 

    Only just now I have figured out what John's code is doing! I didn't understand the fact that Frm2_Closing function is inside the Form1 class.

    My Form2_FormClosing event is in the Form2 class and this is where I added the this.show statement (this is also why I had to declare this funciton public to be able to access it from my button click event in form1 class).

    I fell like a complete idiot now :(

    I have now got the code to run following John's code. Thanks for both of your help!

     

    Wednesday, December 15, 2010 8:38 PM
  • Thanks John!

    Saw your reply just now. I think I was typing my post when you replied. 

    You guys are indeed very helpful. Thanks for your patience!

    Cheers!

    Wednesday, December 15, 2010 8:56 PM