How can I go about closing a Child form if it's already open? And if it isn't already open, then open it?
Thank you
I already have this code, which doesn't work, obviously:
Form ibx = new inbox();
if(ibx.Visible)
ibx.Dispose();
else
ibx.Show();
All that the above does is creates a new form whether or not it's already open.
private Form frm;
public void ToggleForm() {
if(frm == null) {
frm = new Form();
frm.Show();
}
else {
frm.Close();
frm = null;
}
}
If what you want to achieve is opening a form only if it isn't already open, then bring it on front when it is, then the following code might help.
private void tsmiMenuOption_Click(object sender, EventArgs e) {
// Assuming this method is part of an MDI form.
foreach(Form child in this.MdiChildren)
if (child.Name == MyForm.Name) {
child.BringToFront();
return;
}
MyForm f = new MyForm();
f.MdiParent = this;
f.Show();
}
So, this is untested pseudo-c#-code that verifies if MyForm is already opened and contained in the MdiContainer.Children. If it is, then it brings this form (MyForm) to the front. If it is not, then it simply instantiate and opens it.
Is this about what you want?
In your main form, when you create the first childform, keep a reference to it. Currently you're creating a new childform every time you run that code and then you check if the newly created form is visible.
Also be aware that your subject talk about opening and closing but your code seems to just be dealing with hiding and showing.
Carra's code is a good sample how to do it, but be careful if the childform can be closed from anywhere else.
You need to keep a reference to ibx. Your code creates a new inbox everytime it's run.
Module Module1
Public Function InstanceNewForm(ByRef ParentForm As Form, ByRef Childform As Form) As Boolean
Dim bOpen As Boolean = False
Dim frm As Form
For Each frm In ParentForm.MdiChildren
If Childform.Name = frm.Name Then
Childform.Focus()
bOpen = True
Exit For
End If
Next
If Not bOpen Then
With Childform
.StartPosition = FormStartPosition.CenterScreen
.MdiParent = Parentform
.Show()
End With
End If
frm = Nothing
Return bOpen
End Function
End Module
The above code will check to see if a mdi form is already loaded in the parent container and if its already active will set the focus to it. Otherwise it will create the mdi form.
Just call it from anywhere the mdi form needs to be loaded. ex: call InstanceNewForm(me,form2)
Works like a charm everytime!!
Related
I have a WinForm listbox selection of a list of forms that the user can go into.
I have a function that should open the new form
private void sendToDB_Button_Click(object sender, EventArgs e)
{
string selected_item = listBox1.SelectedItem.ToString();
Form _secondForm = new Form();
if (selected_item == "389")
_secondForm = new Forms._389_Form();
else if ( selected_item == "120" )
_secondForm = new Forms._120_Form();
//... Repeat for 30 more forms ...
this.Hide();
_secondForm.Show();
}
When running the application and I select "389" the current form closes as it should but nothing is opened in a new form. Curious if having the forms in a folder called Forms is the issue here. The line in question is _secondForm = new Forms._389_Form(); and is this breaking the application?
Instead of _secondForm.Show(); I changed it to _secondForm.ShowDialog(); and I got the expected results.
According to this link: https://stackoverflow.com/a/20859112/8149159 , The author of the answer states that:
The Show function shows the form in a non modal form. This means that you can click on the parent form.
ShowDialog shows the form modally, meaning you cannot go to the parent form
try
this.Hide();
_secondForm.ShowDialog();
//if you want close precedent form
this.Close();
Hide is for "hide" all action at the user
ShowDialog is for open the form and
Close is for close the precedent form
I'm currently using an MDI Parent Form and inside of it I will open a Form by clicking in one of the items from the ToolStripMenuItem. I have a code which allows me to open that item only one time instead of opening multiple Forms.
frmRegUser frm = null;
private void createToolStripMenuItem_Click(object sender, EventArgs e)
{
if (frm == null)
{
frm = new frmRegUser();
frm.MdiParent = this;
}
frm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
frm.Show();
}
So far so good, but then after closing the Form inside of the MDI Parent Form and try to open the same createToolStripMenuItem again it will displays me an error
Cannot access a disposed object. Name of the object: 'frmRegUser'
Then I searched about it and tried to use a code inside of the frmRegUser closing event put this code:
this.Hide();
this.Parent = null;
e.Cancel = true;
It won't open the form again if I want too.
Do you have any ideia how can I solve this problem?
The problem was solved by removing the this.Parent = null; from the frmRegUser_FormClosing event.
Try this, make sure it's disposed before you initialize:
if (frm == null || frm.IsDisposed)
My problem is:
Main form is opened first, there is a button to open Child form. I use Constructor and I want return a string from Child form to the textbox on Main form, and my code now is:
Form1 f = new Form1(txt1.Text);
f.Show();
But, a new main form will open up, the string won't fill in the first main form.
So how to work with only one main form?
You can do this, get it via OpenForms:
Form1 frm = Application.OpenForms.OfType<Form1>().FirstOrDefault();
Make sure you declare your control txt1 as public on its Modifier property so that you can access it from Child form:
Form1 frm = Application.OpenForms.OfType<Form1>().FirstOrDefault();
frm.txt1.Text = "Change";
frm.Show();
Now if you are trying to change it via its constructor, I doubt you can do it since it was already initialize, unless you call another new Form1 to initialize it and will go through its constructor again.
What you can do is change its property directly:
Form1 frm = Application.OpenForms.OfType<Form1>().FirstOrDefault();
frm.stringMain = "Foo"; //Your property you want to change
frm.txt1.Text = "Change";
frm.Show();
i am writing a code for serial key registration.
if the serial key entered by the user is correct then anothr form must open and the present form must close.
please go thought the code.
namespace ExtTrigger
{
public partial class Activation : Form
{
public Activation()
{
InitializeComponent();
}
private void ActivateButton_Click(object sender, EventArgs e)
{
String key;
key = string.Concat(textBox1.Text,textBox2.Text,textBox3.Text,textBox4.Text);
if (key == "1234123412341234")
{
Properties.Settings.Default.Registered = true;
MessageBox.Show("hurray", "", MessageBoxButtons.OK);
Form1 f1= new Form1();
f1.ShowDialog();
this.Close();
}
else
MessageBox.Show("No Match", "", MessageBoxButtons.OK);
}
private void Activation_Load(object sender, EventArgs e)
{
}
}
my problem is: On clicking on ActivateBotton, Form1 opens but the present form doesnot close.
i have read in few threads that in VB we can change the property: ShutdownMode.
How can we do that in c#?
f1.ShowDialog(); blocks the call, it doesn't go to the next line until that new form has been closed.
An option would be to use:
f1.Show();
Show doesn't block the call, it passes to the next statement. It will not wait for the new form to be closed.
since you have show the second form as f1.ShowDialog() so first one remain open untile second one close, try this
Form1 f1= new Form1();
f1.Show();
this.Close();
The following code should do the trick:
using(Form1 f1 = new Form1())
{
this.Hide();
DialogResult result = f1.ShowDialog();
if(result == DialogResult.OK)
{
this.Show();
}
}
You create your new form within the using-block, then you hide your main form(or the form you are in at the moment) create a DialogResult that gets set by the newly opened form and open this form. Now you can set the results you want to check for inside of your new form and if everything went well inside of you new form you set the DialogResult to OK via:
this.DialogResult = DialogResult.OK;
Now back in our first form you check for the DialogResult and if it is okay you show your main form again. If it was not okay you could just reopen the 2nd form and let the user try again.
Opening a new form is very simple, but the way you do it really depends on your need.
Case 1: I would like to freeze/ block the calling form on secondary form call
In this case you should be using secondaryFormObj.ShowDialog();
Of course, when using this technique your called form, which now acts as a dialog, should "return" an answer to its caller parent on closure.
For example:
private void SecondaryForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Just a dummy code example.
// Always returns Yes result on form closure
this.DialogResult = System.Windows.Forms.DialogResult.Yes;
}
For more help and examples on this manner you can use MSDN:
DialogResult - MSDN
Case 2: I would like to have both forms responding at the same time
In this case you basically need to call secondaryFormObj.Show();
If you want the caller form to be hidden on secondary form call, just
invoke this.Hide();
after the call to secondaryFormObj.Show(); in the caller class.
You can also close the caller form using this.Close(); as long as the caller form is not the application's main form.
... And remember
Always make sure you initialized the secondary form object before
invoking it with either secondaryFormObj.Show(); or
secondaryFormObj.ShowDialog();
Initializing a form is done the same way like every typical object using the
new operator.
For example: secondaryFormObj = new Form();
Hopes this helps. Happy coding!
I'm working on an application and I've encountered a strange issue, that I think should be simple, but isn't. What I'm trying to accomplish is set the main form's title caption to a specific value when the another form closes. Below is my most recent attempt at this.
// From the main form I have
ObjectForm Objects = new ObjectForm();
Objects.GameName = this.Text; // this is a public string on the ObjectForm side
// Here is what I have on the ObjectForm
private void btnOK_click(object sender, EventArgs e)
{
MainForm Main = new MainForm();
Main.Text = this.txtGameName.Text;
this.Close();
}
Any help will be gladly accepted, thanks :D
You can't just instantiate a new MainForm, you need to get a reference to the existing instance.
Have a look in the documentation at Application.OpenForms
This code you have in your button click handler
MainForm Main = new MainForm();
Main.Text = this.txtGameName.Text;
Instantiates a new MainForm and sets it's title, this is completely separate instance to the MainForm that houses your application.