C# Using One Panel As a Placeholder For Multiple Forms - c#

I apologize if this has been addressed already, but I could not find a case that fit my exact situation. So here goes...
I have a MainForm that contains a toolStrip1 docked to the left that functions as a vertical navigation bar. I have a panel (pnlMain) filling up the remainder of the form. I want to use pnlMain to display different forms which are made up of win form classes. Right now, I can click on the labels/buttons on toolStrip1 to display different forms within pnlMain.
private void tsLblCustomers_Click(object sender, EventArgs e)
{
hidePanels();
CustomerReport cr = new CustomerReport();
cr.TopLevel = false;
cr.AutoScroll = true;
cr.BackColor = Color.White;
pnlMain.Controls.Add(cr);
cr.Show();
}
What I want to do now is display additional forms within pnlMain by clicking on a button on another form rather than a label/button on toolStrip1. Some of my forms are as follows: CustomerReport, AddCustomer, EmployeeReport, AddEmployee. The Report forms are linked to my tool strip buttons. The Add forms are linked to buttons on the Reports forms. I tried several things including the following:
1) On CustomerReport, I tried creating an instance of MainForm, then I'll create an instance of AddCustomer, and then add that instance to the panel on MainForm.
2) I also tried creating a method in MainForm to create the instance of AddCustomer, and then call that method from the Add button on CustomerReport. Even though the code was the same as the toolstrip buttons on MainForm, it did not work.
I tried different variations of hiding forms, showing forms, clearing the panel, setting Visible to true or false, and I can't get it to work right. In some cases, I've managed to hide the CustomerReport, but AddCustomer will not come up. At some point I think I created a NEW instance of MainForm and my code wasn't impacting the original form that is already open. I'm just lost. Should I be using a different design? Originally I set up my application to just hide one form then show the other but I read that that is a 'terrible design'.

This sounds very similar to this thread here: Creating Form Inside the Form
You'd want to look into MDI.
Although it sounds like you're aiming for one cohesive interactive window. Otherwise, if you just want separate windows to popup, you can create properties within that other form and read them after returning a DialogResult. I'm not sure why this would be bad design without knowing more about the context of the program.
//Optionally do a hide(); here.
AddCustomer customer = new AddCustomer();
DialogResult result = customer.ShowDialog();
if(result == DialogResult.OK)
{
var name = customer.Name;
//More properties or whatever here.
}
//The properties would still be accessible here, too.

I ended up keeping the toolstrip nav bar on the left side of the primary window, and I created a panel in the main part of the window. All forms are displayed in the panel. Each time one of the label options in the nav bar is clicked on, the current form is cleared off the panel and the active form is displayed.
private void tsLblCustomers_Click(object sender, EventArgs e)
{
pnlMain.Controls.Clear();
CustomerReport cr = new CustomerReport();
cr.TopLevel = false;
cr.AutoScroll = true;
cr.BackColor = Color.White;
pnlMain.Controls.Add(cr);
cr.Show();
}
private void tsLblEmployees_Click(object sender, EventArgs e)
{
pnlMain.Controls.Clear();
EmployeeReport emp = new EmployeeReport();
emp.TopLevel = false;
emp.AutoScroll = true;
emp.BackColor = Color.White;
pnlMain.Controls.Add(emp);
emp.Show();
}
private void tsLblVendors_Click(object sender, EventArgs e)
{
pnlMain.Controls.Clear();
VendorReport vend = new VendorReport();
vend.TopLevel = false;
vend.AutoScroll = true;
vend.BackColor = Color.White;
pnlMain.Controls.Add(vend);
vend.Show();
}
private void MainForm_Load(object sender, EventArgs e)
{
WelcomeForm welcome = new WelcomeForm();
welcome.TopLevel = false;
welcome.AutoScroll = true;
welcome.BackColor = Color.White;
pnlMain.Controls.Add(welcome);
welcome.Show();
}

Related

Update Controls in Form 1 from Form 2 that was Created by Form 1

I checked and found this article that is referred to MANY times in this type of question, and it is NOT the answer I want...
I have a form, Form_Main frmMainPage, it creates Form_Status frmStatus.
When it does so, I disable the controls on frmMainPage so the user can't mess with things while things are processing.
When things are done processing they can close the frmStatus window to go back to frmMainPage to continue working. I cannot re-enable the controls from frmStatus. I tried to use the frmMainPage_Enter, but it goes crazy when it first loads, so that isn't really an option.
I have the following in Form_Main.cs
public void EnableForm() {
this.gridData.Enabled = true;
this.txtLocation.Enabled = true;
this.txtSupplier.Enabled = true;
this.txtItem.Enabled = true;
this.FillTable("", "", "");
}
When I use this (per article above):
private void btnClose_Click(object sender, EventArgs e) {
Form_Main f2 = new Form_Main();
f2.Show();
f2.EnableForm();
this.Close();
}
It creates a second Form_Main, which is not what I want. I want to know how to change the controls in the existing form.
Edit: No, it is not this that was also suggested. Most of the answers deal with changing controls on Form 2 from Form 1 when Form 2 is created by Form 1. In my case I need to do the opposite and change controls on Form 1 FROM Form 2, which was created by Form 1. Kind of a circular thing.
I can think of a couple of ways to do this. First (and most common) is to show the second form modally (which means that the first form's code pauses while the second form's code is running):
private void button1_Click(object sender, EventArgs e)
{
var statusForm = new frmStatus();
// ShowDialog will prevent frmMainPage from being accessible.
// This form's code will pause at the next line until the second form is closed
statusForm.ShowDialog();
}
There are occasions where you want to have both forms accessible at the same time. If this is the case, another method would be to add an event handler for the second form's FormClosed event, where you can re-enable the controls on the first form. This will allow both forms to be accessed at the same time:
private void button1_Click(object sender, EventArgs e)
{
var statusForm = new frmStatus();
// Add an event handler for the second form's FormClosed event, and
// put code in that event handler to re-enable controls on this form
statusForm.FormClosed += statusForm_FormClosed;
// Disable our controls on this form and show the second form
DisableForm();
statusForm.Show();
}
private void statusForm_FormClosed(object sender, FormClosedEventArgs e)
{
// When the second form closes, re-enable controls on this form
EnableForm();
}
private void DisableForm()
{
this.gridData.Enabled = false;
this.txtLocation.Enabled = false;
this.txtSupplier.Enabled = false;
this.txtItem.Enabled = false;
}
public void EnableForm()
{
this.gridData.Enabled = true;
this.txtLocation.Enabled = true;
this.txtSupplier.Enabled = true;
this.txtItem.Enabled = true;
this.FillTable("", "", "");
}
you dont need to do this disable enable.
you just need to show your new from with ShowDialog(); like this:
frmStatus.ShowDialog();
instead of just:
frmStatus.Show();

C# Forms Show/Hide

In VB.NET, you can freely Hide/Show/ShowDialog (for a fresh form). But in C#, you always have to create new form instance to do this. Even your previosly hidden form can't show back, you have to create new instance again. Resulting in your previously hidden form will run as background process until you kill it.
My question is how can I create a function that will unhide a form that doesn't need a new instance when I close the current form using the default exit in form's title bar.
Edit: I solved it on my own. It's just confusing. And what difference between c# and vb.net is that I never have to use form_closed in vb.net. Why do I always see it in c#.
You can always display an hidden form in C#. There are many ways to this.
For example you could check the Application.OpenForms collection that keeps track of all forms owned by your application and still not closed. (An hidden form is not closed). This approach means that you need to identify you form between the ones included in the collection OpenForms
MyFormClass f = Application.OpenForms.OfType<MyFormClass>().FirstOrDefault();
if ( f != null) f.Show();
Another approach, more lengthy, is to keep track yourself of the form to hide/show with a variable inside your application. This requires extra care in handling correctly the various situations in which you global variable becomes invalid (what if the user closes effectively the form instead of hiding it?)
This is an example that you can test easily with LinqPAD
// Your form instance to hide/show
Form hidingForm = null;
void Main()
{
Form f = new Form();
Button b1 = new Button();
Button b2 = new Button();
b1.Click += onClickB1;
b2.Click += onClickB2;
b1.Location = new System.Drawing.Point(0,0);
b2.Location = new System.Drawing.Point(0, 30);
b1.Text = "Hide";
b2.Text = "Show";
f.Controls.AddRange(new Control[] {b1, b2});
f.ShowDialog();
}
void onClickB1(object sender, EventArgs e)
{
// Hide the global instance if it exists and it is visible
if(hidingForm != null && hidingForm.Visible)
hidingForm.Hide();
}
void onClickB2(object sender, EventArgs e)
{
// Create and show the global instance if it doesn't exist
if (hidingForm == null)
{
hidingForm = new Form();
hidingForm.Show();
// Get informed here if the user closes the form
hidingForm.FormClosed += onClosed;
}
else
{
// Show the form if it is not visible
if(!hidingForm.Visible)
hidingForm.Show();
}
}
void onClosed(object sender, FormClosedEventArgs e)
{
// Uh-oh.... the user has closed the form, don't get fooled...
hidingForm = null;
}
Well, OpenForms seems a lot better.

Hide/Show Tab Pages C#

I've been trying so hard to show the tab pages, actually hide the tab pages is working but show i tried everything but nothing successfully here's the code:
this is how i call the form that the user puts his password:
private void adminToolStripMenuItem1_Click(object sender, EventArgs e)
{
Password pss = new Password();
pss.Show();
}
this is the button that have to add the Tab-Page:
private void btnGo_Click(object sender, EventArgs e)
{
if(String.IsNullOrWhiteSpace(txtGo.Text))
{
lblErro.Text = "Type the password.";
return;
}
if(txtGo.Text != Properties.Settings.Default.Pass)
{
lblErro.Text = "Incorrect password.";
return;
}
else
{
this.Close();
MainForm main = new MainForm();
main.operatorToolStripMenuItem1.Checked = false;
main.adminToolStripMenuItem1.Checked = true;
main.accountPermissionsAdm();
}
}
this is the function i created to the account permissions when the user is admin:
public void accountPermissionsAdm()
{
if (!settings)
tabControl_Config.TabPages.Add(tabPage_Report);
if (!pathLoss)
tabControl_Config.TabPages.Add(tabPage_PathLoss);
if (!instrument)
tabControl_Config.TabPages.Add(tabPage_Instrument);
if (!parameters)
mainTabControl.TabPages.Add(tabPage_DefineParameters);
if (!scenario)
mainTabControl.TabPages.Add(tabPage_RunScenario);
if (!customer)
mainTabControl.TabPages.Add(tabPage_CustomerId);
IntPtr h = this.tabControl_Config.Handle;
tabControl_Config.TabPages.Insert(3, tabPage_RunCondition);
}
UPDATE - after reading your edited question with more code:
Few potential problems:
In btnGo_Click you are calling this.Close(); which returns, so the rest of the code in this else statement is unreachable.
Even if you will not call this.Close();, the code has no practical meaning, as you are creating a new instance of MainForm but you didn't show it (either by calling main.Show() or main.ShowDialog()).
Not sure if that's the flow, but it looks like Password is a child of your main form (MainForm). If that's the case, you should change the behavior so that, for example (there are other approaches) Password will return some value (boolean for example) that the main form needs to be changed (insertion of TabPage etc.). The change then must be performed on the main form and not from other forms.
Please follow these guidelines and make the changes, or consider of a new design, as it seems very broken to me.
Original answer (how to hide/show tab page)
I'm afraid you can't hide TabPage. You will have to remove and add it again. For example, like this:
Hide:
this.tabControl1.TabPages.Remove(tabPage1);
Show:
this.tabControl1.TabPages.Add(tabPage1);
The reason is that the Hide() function will have no effect in this situation, according to MSDN:
TabPage controls are constrained by their container, so some of the
properties inherited from the Control base class will have no effect,
including Top, Height, Left, Width, Show, and Hide.

How to use MdiContainer

This is what I usually do when I want to open a new form from a ToolStripMenu
private void alumnoToolStripMenuItem_Click(object sender, EventArgs e)
{
frmAlumno x = new frmAlumno();
x.ShowDialog();
}
but a teacher told me that it´s wrong because this shouldn´t happen..
So I guess I have to use MdiContainer but I´m not sure of how to write the code now... Please some help...
If you use MDI, you should call Show, not ShowDialog. Also you need to set MdiParent.
Form2 newMDIChild = new Form2();
// Set the Parent Form of the Child window.
newMDIChild.MdiParent = this;
// Display the new form.
newMDIChild.Show();
How to: Create MDI Child Forms
I'm going to answer with a solution to your actual problem instead of describing how to use MdiContainer, since you don't actually need it. :)
Forms have a ShowInTaskbar property that defaults to true. Set it to false and the form will no longer appear in the task bar.
private void alumnoToolStripMenuItem_Click(object sender, EventArgs e)
{
frmAlumno x = new frmAlumno();
x.ShowInTaskbar = false;
x.ShowDialog();
}
See MSDN for more information.
Introduction to MDI Forms with C#

C#.NET MDI bugs when programmatically hiding and showing again a maximized child form and when maximized, child form's icon cannot be changed

Basically I am having two problems with C#.NET MDI. You can download VS2010 solution which reproduces bugs here.
1) When programmatically hiding and showing again a maximized child form, it is not maximized properly again and becomes neither maximized or in normal state.
childForm = new Form();
childForm.Text = "Child Form";
childForm.MdiParent = this;
...
private void showButton_Click(object sender, EventArgs e)
{
childForm.Visible = true;
}
...
private void hideButton_Click(object sender, EventArgs e)
{
childForm.Visible = false;
}
When child form is maximized, then programicaly hidden and shown again, it becomes something like this (please notice the menu bar - child form's control box appears, but child form is not maximized):
At this stage, child form cannot be moved around. However, I found a workaround for that, simply by showing and hiding a dummy child form, which forces the actual child form to become properly maximized. But this makes MDI area to flicker. Tried Invalidate, Refresh, Update methods, but they don't help. Maybe there are other workarounds to overcome this bug and not to make MDI area flicker with dummy child form?
private void workaround1Button_Click(object sender, EventArgs e)
{
dummyForm.Visible = true;
dummyForm.Visible = false;
}
2) When child form is maximized, the icon of the child form is displayed on menu bar. However, if you have to change the icon while the child form is maximized, the icon on the menu bar is not being refreshed (see the image above). I found a workaround for that too, which basically hides and shows menu bar. Icon gets refreshed, but it makes everything below menu bar to flicker. Tried Invalidate, Refresh, Update methods, but they don't help. Is there any other way to make menu bar to refresh the child form's icon?
private void workaround2Button_Click(object sender, EventArgs e)
{
menuStrip.Visible = false;
menuStrip.Visible = true;
}
Also I noticed that when parent form is in normal window state mode (not maximized) and you change the width or height of the form by 1 pixel, child form becomes maximized as it should be and child form's icon on menu bar gets refreshed properly and you don't need other workaround I described above. If I change the size of the form programicaly, form flickers by 1 pixel and I cannot do that, when parent form is maximized. Is there any way how I could invoke the repaint/refresh functionality which is called when you resize a form and which makes child form become maximized properly and the icon on the menu bar refreshed?
There's a bug in the implementation of the internal MdiControlStrip class, the control that displays the icon and the min/max/restore glyphs in the parent window. I haven't characterized it as yet, the code isn't that easy. A classic side effect of the bug is that the glyphs get doubled up, you found some other side-effects. The fix is simple though, delay creating the child windows until after the constructor is completed. Like this:
public MainForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e) {
childForm = new Form();
childForm.Text = "Child Form";
childForm.MdiParent = this;
dummyForm = new Form();
dummyForm.MdiParent = this;
dummyForm.WindowState = FormWindowState.Maximized;
base.OnLoad(e);
}
Have you tired using Hide/Show instead of setting visible to true/false?
Try:
private void showButton_Click(object sender, EventArgs e)
{
childForm.Show();
}
private void hideButton_Click(object sender, EventArgs e)
{
childForm.Hide();
}
How about this workaround?
private void showButton_Click(object sender, EventArgs e)
{
childForm.Visible = true;
childForm.WindowState = (FormWindowState)childForm.Tag;
}
private void hideButton_Click(object sender, EventArgs e)
{
childForm.Visible = false;
childForm.Tag = childForm.WindowState;
childForm.WindowState = FormWindowState.Normal;
}
UPDATE
I just gave you the idea how you could do. A better solution using the same idea as above would be a new base form which saves the windows state. See below. Derive your forms from FixedForm instead of Form:
public partial class FixedForm : Form
{
private FormWindowState lastWindowState;
public FixedForm()
{
InitializeComponent();
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (Visible)
{
WindowState = lastWindowState;
}
else
{
lastWindowState = WindowState;
WindowState = FormWindowState.Normal;
}
}
}
Found a way how to come around those bugs.
First of all you need to suspend painting for a form and its children. I found a very helpful thread here, which describes how to do it.
After suspending painting, you need call UpdateBounds method of the control and increase ClientRectangle Width or Height by one and then decrease it back to the same value it was before. This invokes layout functionality which makes everything to update/repaint. Last step is to enable painting. Not very nice solution I guess, but it works.
StopDrawing();
UpdateBounds(Location.X, Location.Y, Width, Height, ClientRectangle.Width, ClientRectangle.Height + 1);
UpdateBounds(Location.X, Location.Y, Width, Height, ClientRectangle.Width, ClientRectangle.Height - 1);
StartDrawing();
I find suspending painting very helpful not only for working around those two bugs, but also in general to make GUI work more smoothly. I guess this can help to remove any kind of flickering. However, this solution requires P/Invokes, which should be avoided in general.
Why not just manually reset required icon in menuStrip items, after the creation of the window:
menuStripMain.Items[0].Image = null;

Categories