In my main form I am opening a new form (lets call it the parent form) using ShowDialog(). In the parent form I have a button which loads an OpenFileDialog, when I load the image and click Open button, OpenFileDialog closes but it also closes the parent window and I dont want this to happen.
Main form code:
// ADD GRAPHICS BUTTON
private void bAddGraphics_Click(object sender, EventArgs e)
{
NewGraphics newGraphics = new NewGraphics();
newGraphics.ShowDialog();
if (newGraphics.DialogResult == DialogResult.OK)
{
Core.Graphics tempGraphicsObject = new Core.Graphics();
tempGraphicsObject.name = newGraphics.name;
tempGraphicsObject.background = newGraphics.bgImage;
core.NewGraphics(tempGraphicsObject);
generateSingleGraphicsControl(core.project.graphics[core.project.graphics.Count-1].id, core.project.graphics[core.project.graphics.Count-1].name);
}
newGraphics.Dispose();
}
Parent form(dialog)
OpenFileDialog openFileDialog = new OpenFileDialog();
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
tbBackground.Text = openFileDialog.FileName;
bgImage = Image.FromFile(tbBackground.Text);
}
openFileDialog.Dispose();
Is it because I use DialogResult twice or maybe because I call ShowDialog() in a dialog window ? If I won't use ShowDialog() on a parent but just Show() it works fine but then I can't use DialogResult property. Is there a way around it or you just can't use ShowDialog() twice ?
If the "parent" Form is closing too, then you're either calling Close() or setting the DialogResult property on the Form (which will also close it).
From MSDN, regarding the DialogResult property:
If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form.
I don't see you doing either one of those in the code you posted, but check for a line like one of these in your "parent" Form:
DialogResult = DialogResult.OK;
this.DialogResult = DialogResult.Cancel;
Close();
this.Close();
I know I'm digging up an old post, but I just ran into this and found another situation that can cause this. It's common to copy/paste form controls and reuse them for other purposes. Make sure that if you copied your form's OK or Cancel button for the Browse File button that you remove the DialogResult value. I had done this and forgot to remove the DialogResult.OK from my folder browser button. Apparently, the DialogResult assignment will happen after the click event making it appear that the dialog closed its parent.
Related
I have a form that I open using ParentForm.ShowDialog().
Inside this form I call:
using (var form = new ChildForm())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
this.Cancelled = false;
}
}
I'm getting odd behavior when the child dialog is closed, the parent (calling) form also closes.
Why is this happening and how do I stop it?
I have a current solution that prevents the closing of the parent form by using the ParentForm_FormClosing event and a Boolean, but it feels like an over complicated solution
A form opened modally is closed when you set the property DialogResult to anything but DialogResult.None. The common practice to close a modal form is to set the DialogResult property of one or more buttons to some value of the same named enum. In that way, when the form engine sees a call to a click event handler checks the value of the DialogResult of the clicked button and, if nothing change that value, it closes the form when the click event handler ends returning that enum value to the caller.
So, you probably have copy/paste that button leaving the original DialogResult property unchanged and clicking that button will trigger the closure of the hosting form.
Of course before closing the hosting form, the engine will call the button click event in which you open a modal dialog and this suspends everything until you close the child form. At that point the code exits the click event and the form engine continue closing your parent form returning to the caller the value of the DialogResult property of the button.
If you don't want to automtically close the hosting form then you can set the form's DialogResult in code with
this.DialogResult = DialogResult.None;
or change the value of the button's DialogResult property
I have a form that I use the ShowDialog() method to bring up so the user can't change control back to the main form, and on the sub form I have a MessageBox.Show() method call which returns a DialogResult.
Only problem is, no matter what the dialog result of the message box, it causes my sub form to close. Is there a behaviour I am overlooking or is there something the matter with my code?
The code in the main form to open the sub form:
private void btnScanFree_Click(object sender, EventArgs e)
{
frmScan scanForm = new frmScan();
scanForm.ShowDialog();
}
And the code in the cancel button click method on the sub form:
private void btnCancel_Click(object sender, EventArgs e)
{
if (dgvScannedItems.RowCount > 0)
{
DialogResult dr = MessageBox.Show("There are scanned items that have not been inserted to the database. Are you sure you want to go back?", "Go Back", MessageBoxButtons.YesNo);
if (dr == System.Windows.Forms.DialogResult.Yes)
{
this.Close();
}
}
else
{
this.Close();
}
}
On the sub form, if there are no rows in the data grid view, then the form should close, otherwise a message box should appear with yes and no buttons and a question asking the user if they want to continue closing the form. But whether they press yes or no, it closes both the message box (which it always should) and the sub form (which half the time it should not).
BtnCancel is a dialog Button and sets DialogResult of the form to cancel or no or something similar. Since you have opened the form as a dialog via ShowDialog setting the DialogResult Causes the form to close and return the result.
So you need to set the DialogResult property of the BtnCancel to nothing to prevent this "starnge" behaviour.
Why not add a watch on dgvScannedItems.RowCount and see what the value is?
In an answer to a recent question I had (Here), Hans Passant stated that I should set the DialogResult to close my forms instead of form.Close() although I cannot seem to find out why?
If I've read correctly, the MSDN documentation states that doing this will just hide the form instead of correctly disposing it which I believed .Close() to do?
Extract from documentation.
The Close method is not automatically called when the user clicks the Close button of a dialog box or sets the value of the DialogResult property. Instead, the form is hidden and can be shown again without creating a new instance of the dialog box. Because of this behavior, you must call the Dispose method of the form when the form is no longer needed by your application.
On the other hand, Microsoft has created a support page that says how to use DialogResult property and in the "Verify It Works" section of this it states that clicking so will Close the form.
So my question is two fold, should I continue to use Close or DialogResult instead; and does dialog result close or hide a form. From the code I made below (a simple form with two buttons), it would seem that it is indeed hidden only as a breakpoint on this.Close() is hit..(with this.Close() commented, the form still disappears, just not sure whether hidden or not)
public Form1()
{
InitializeComponent();
button1.Click += (s, e) =>
{
//I edited my question to include using
using(Form1 form = new Form1())
{
form.ShowDialog();
}
};
button2.Click += (s, e) =>
{
this.DialogResult = DialogResult.OK;
this.Close();
};
}
When you open a modal dialog with ShowDialog, the calling code is blocked until the form called closes or hides. If you want to read some public properties of the called form and want to do things (for example save data to a database or to a file) based on the click on the OK or Cancel button, then you need to know if the user wants to do the action or not. The DialogResult returned by the ShowDialog() method allows you to take the appropriate actions...
So for example
using (Form1 form = new Form1())
{
DialogResult dr = form.ShowDialog();
if(dr == DialogResult.OK)
{
string custName = form.CustomerName;
SaveToFile(custName);
}
}
An important thing to add to this answer is the fact that the DialogResult property exists both on the Form class and in the Button class. Setting the button's DialogResult property (both via code or designer) to a value different from DialogResult.None is the key to activate an important behavior for forms. If you click a button with that property set then the Forms Engine transfers the value of the Buttons property to the Forms one and triggers the automatic closure of the form reactivating the caller code. If you have an event handler on the button click then you can run code to validate the form's inputs and force the form to stay open overriding the form's DialogResult property setting it back to DialogResult.None
For example, in the modally showed form you can have:
// Event handler for the OK button set with DialogResult.OK
public void cmdOK_Click(object sender, EventArgs e)
{
// Your code that checks the form data and
// eventually display an error message.
bool isFormDataValid = ValidateFormData();
// If data is not valid force the form to stay open
if(!isFormDataValid)
this.DialogResult = DialogResult.None;
}
Whether you call Close or set the DialogResult property is not really the issue. You just need to make sure to call Dispose. I prefer doing this with a using block:
using (Form1 form = new Form1())
{
form.ShowDialog();
}
I originally thought that you could call ShowDialog on a Form that has already had its Close method called. This is not the case. If you show the form modally with ShowDialog, it doesn't seem to matter whether it is closed as a result of the Close method, or setting the DialogResult property. It would seem that setting the DialogResult is just a short-cut for closing the Form.
But whether you call Close or set the DialogResult property, the key is to make sure that you call Dispose() or put your form in a using block.
In a multiple projects solution I had a startup WinForms project with 2 Forms, expecting a DialogResult whenever the child Form was shown to continue execution in my main Form.
var form2 = new ThisNameSpace.FormChild();
var dResult = form2.ShowDialog(this);
if(dResult == DialogResult.OK)
{
// Do some work
}
else
{
// Do other work
}
For some reason, I had to move the child Form in another project. I've referenced the new Project's dll in my main startup Form project but I'm now unable to return a dialog result. When my child Form closes the FormClosing event of the main Form is raised with CloseReason.None and the application exits. How can I work this around?
You should not raise FormClosing event yourself, and you should not write any custom code to just close the dialog.
Instead do this:
on your OK button in child form, set DialogResult property to OK
on your child form, set set Accept Button property to point to your OK button
that's all you need to close the window and correct DialogResult will be returned.
If you ever need to close it 'manually' (and this is rare for modal dialogs, i.e. those opened with ShowDialog instead of Show), use Close method.
I have a windows form that pops up a dialog box if certian conditions are met when the form loads. The problem is the window does not stay on top and I can still click thing on the parent. However, there is a button on the form that when pressed opens the same window, when I do this it works as expected (like a dialog window).
Is there an issue with showing a dialog when a form is first loading?
Are you calling ShowDialog from the Form class? Because it will only set the parent window if called from another Form. Alternatively you can use the overload that has the IWin32Window parameter to specifically set the owner.
can you explain the issue further as this is my code which do not show the form it self until the dialog has been closed either you set the parent or not
private void Form1_Load(object sender, EventArgs e)
{
//your functionality goes here
AboutBox1 box = new AboutBox1();
box.ShowDialog();
}
}
on the other side you can also check with TopMost property
The ShowDialog method needs to be called from the form that you want to be it's parent/owner in order for it to be modal to that form. Alternatively I believe you can set the owner of a dialog directly but I have never needed to do that.
DaBomb,
To do what you want, you will have to call your modal dialog from the constructor of your main form, NOT from the Form_Load event.
Something like this:
public Form1()
{
InitializeComponent();
this.Show();
Form2 popupForm = new Form2();
popupForm.ShowDialog();
}