Close YesNo MessageBox C# - c#

It (MessageBox) checks if a file is saved or not
I want to close the Form when clicking Yes
and to return to the app when clicking No
I searched a lot in the documents and questions but didn't find an answer
I mean, there is "MessageBox.Show()",
Isn't there "MessageBox.Close()" ??
That's what I have:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
var message = "The File Is Not Saved\nDo You Want To Close?";
var title = "File Not Saved";
var buttons = MessageBoxButtons.YesNo;
if (FSaved == false)
{
var res = MessageBox.Show(message, title, buttons);
if (res == DialogResult.Yes)
{
this.Close();
}
else if (res == DialogResult.No)
{
return;
}
}
}

You have you cancel the close with the event args - e.
e.Cancel = true;
You also shouldn't call Close() from FormClosing as it is already on the way out.

Related

I need to validate Tabcontroll in winform c#, I want show a message before selecting another tab

I want to show a message before selecting another tab if Message result is 'NO' then it should remain in the current tab if message result is YES then selected tab should open.
I have tried following code.
''
'private void tbRWINV_Selected(object sender, TabControlEventArgs e){
if (dgvSaleReturnWintoutInvoice.Rows.Count > 0)
{
DialogResult msg = new DialogResult();
msg = MessageBox.Show("The data entered for return will be lost if you move to other Tab", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (msg == DialogResult.No)
{
tbRWINV.TabIndex = 1;
}
}
}
'''
The TabControlCancelEventArgs event object has a bool Cancel property that will cancel the tab change. E.g:
public class MyForm : Form {
TabControl tc = new TabControl();
public MyForm() {
//...
tc.Selecting += tc_Selecting;
}
void tc_Selecting(object sender, TabControlCancelEventArgs e) {
DialogResult r = MessageBox.Show(this, "Are you sure you want to change tabs?", "Confirm", MessageBoxButtons.YesNo);
e.Cancel = (r == DialogResult.No);
}
}

C# Button with DialogResult Retry

I'm going to use two buttons that have a DialogResult Retry. When you push the button the winform will hide, do something and it pops-up again. I use the While method for this. But if you have two buttons with a retry this won't work unless you set one button DialogResult to Yes and do a While method. But is there a better way to do this, case switch or something?
Note this is within a Class
try
{
// Create a form to select objects.
DialogResult result = System.Windows.Forms.DialogResult.None;
while (result == DialogResult.None || result == DialogResult.Retry)
{
// Picking Objects.
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
var dialogResult = saveFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
string address = "http://www.autodesk.com/revit-basic-sample-family-2017-enu?_ga=2.28765692.1750602280.1538397390-459409917.1521646598";
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(address, saveFileDialog1.FileName);
Autodesk.Revit.DB.Family family = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Load Family");
if (doc.LoadFamily(saveFileDialog1.FileName, out family))
{
String name = family.Name;
TaskDialog.Show("Revit", "Family file " + name + " has been loaded ");
}
else
{
TaskDialog.Show("Revit", "Can't load the family file or already exists.");
}
tx.Commit();
}
}
if (dialogResult == DialogResult.Cancel)
{
}
}
// Show the dialog.
using (testForm selectionForm = new vuurenForm(commandData))
{
result = selectionForm.ShowDialog();
}
}
return Result.Succeeded;
You may set the DialogResult in the code, not in the form designer. Just double click the buttons and add something like:
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Retry;
}
That way both buttons will have the same DialogResult.
Than the loop is OK with only checking for the DialogResult.Retry.
Exactly you can try this code to manage your DialogResult like:
switch(MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo))
{
case DailogResult == DialogResult.Yes:
//Do something
case DailogResult == DialogResult.Retry:
//Do something
}
Actually for two Button objects you have to have two event-handler objects and you can set:
DialogResult = DialogResult.Retry;
In the event that you want to Retry.
You can try this:
var dialogResult = DialogResult.Retry;
while (dialogResult == DialogResult.Retry) {
try {
CheckSomething();
break;
}
catch {
if (dialogResult == DialogResult.Abort) {secondDialog.DialogResult = Retry;}
throw;
}
}
You can also use enums like below:
enum Result {Ignore, Abort,Retry};

VS2015 Closing Windows Form not working properly

I have VS2015 Windows Form, and whenever I click X to close application, it prompts me to close it or not. When I press No, then the pop up window would close. However, when I press Yes, it pops up another same window, and asks me to close it or not.
How can I solve this issue? I want to close my form at first popup.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
const string closemsg = "Do you really want to close the program?";
const string exit = "Exit";
DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}
It is very simple.
Make remove Application.Exit();
Application.Exit() generates the FormClosing event.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
const string closemsg = "Do you really want to close the program?";
const string exit = "Exit";
DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
//Remove Application.Exit();
//Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}
However, when I press Yes, it pops up another same window, and asks me to close it or not.
The reason is because your Form1_FormClosing will be called again. Try setting a _isExiting flag that you can test upon entry.
Try this:
bool _isExiting;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_isExiting)
{
// whoops, been here already, time to go!
return;
}
const string closemsg = "Do you really want to close the program?";
const string exit = "Exit";
DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
_isExiting=true; // set flag here so we don't repeat this exercise again
Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}

I want to check which button was clicked

Right now I have a main form that copies a file to another directory.
I want to handle the case 'a file of the same name already exists' in a catch statement.
I want this to be done by it popping up another window asking whether to replace or keep via buttons. Then using an if statement to check which button was clicked
Current code:
catch (IOException x)
{
Copy copy = new Copy();
copy.ShowDialog();
}
Goal:
catch (IOException x)
{
Copy copy = new Copy();
copy.ShowDialog();
if (//Replace button was clicked)
do this
else if (//Keep button was clicked)
do this
}
I can't seem to find the methods that serve this purpose.
You could make your Copy dialog return the DialogResult when the button is clicked. For instance you could use DialogRsult.OK for the Replace button and the DialogResult.Cancel for the Keep button. Something like this:
When clicked Replace button within the Copy dialog you can set this within the Replace_Click event handler
this.DialogResult = DialogResult.OK;
this.Close();
set in the similar way the DialogResult.Cancel in the Keep_Click event handler
and you could call your dialog like this:
Copy copy = new Copy();
DialogResult dr = copy.ShowDialog();
if(dr == DialogResult.OK)
//Replace clicked
else if(dr == DialogResult.Cancel)
//Keep clicked
You should consider using the DialogResult class instead.
You want something like this:
catch (IOException x)
{
DialogResult dr = new DialogResult ();
dr.ShowDialog();
if (dr == DialogResult.OK)
MessageBox.Show ("File replaced.");
else if (dr == DialogResult.Cancel)
MessageBox.Show ("File kept.");
}
Do not use exceptions to handle this kind of situations.
Just test if file exists and use a simple MessageBox with YesNo buttons
sourceFile = "Your_Source_File_To_Copy";
string destFile = Path.Combine(destFolder, Path.GetFileName(sourceFile));
if(File.Exists(destFile))
{
DialogResult dr = MessageBox.Show("File already exist! Do you wish to overwrite?",
"Warning!",
MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes)
// Overwrite
else
// Do something else
}
As Mr Lippert says in this answer,
Exceptions are there to
help you debug your program, not to control its flow.
Have you looked into the Form.ShowDialog method?
http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx
Code Excerpt from MSDN:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
Check for the file existence before copying:
if (File.Exists(destFileName))
{
Copy copy = new Copy();
System.Windows.Forms.DialogResult res = copy.ShowDialog();
if (res == System.Windows.Forms.DialogResult.Yes)
File.Copy(sourceFileName, destFileName, true);
}
else
{
File.Copy(sourceFileName, destFileName);
}
Also set the DialogResult property in the Copy form appropriately.
Perhaps implementing your own result is what you are looking for.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var result = new Form2().ShowDialog();
MessageBox.Show(result.ToString());
}
}
public partial class Form2 : Form
{
ButtonResult buttonResult;
public Form2()
{
InitializeComponent();
}
public new ButtonResult ShowDialog()
{
base.ShowDialog();
return buttonResult;
}
private void KeepButton_Click(object sender, EventArgs e)
{
buttonResult = ButtonResult.Keep;
this.Close();
}
private void ReplaceButton_Click(object sender, EventArgs e)
{
buttonResult = ButtonResult.Replace;
this.Close();
}
}
public enum ButtonResult
{
None = 0,
Keep = 1,
Replace = 2,
}

How to prevent or block closing a WinForms window?

How can I prevent window closing by showing a MessageBox? (Technology:WinForms with C#)
When the close event occurs I want the following code to be run:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
//close addFile form
} else {
//ignore closing event
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
var window = MessageBox.Show(
"Close the window?",
"Are you sure?",
MessageBoxButtons.YesNo);
e.Cancel = (window == DialogResult.No);
}
Catch FormClosing event and set e.Cancel = true
private void AdminFrame_FormClosing(object sender, FormClosingEventArgs e)
{
var res = MessageBox.Show(this, "You really want to quit?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (res != DialogResult.Yes)
{
e.Cancel = true;
return;
}
}
A special twist might be to always prevent just the user closing the form:
private void Frm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = (e.CloseReason == CloseReason.UserClosing);
// disable user closing the form, but no one else
}
Within your OnFormClosing event you can show the dialog and if answer is false (to not show) then set the Cancel property of the EventArgs to true.
For prevent or block the form closing in particular situation you can use this strategy:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (FLAG_CONDITION == true)
{
MessageBox.Show("To exit save the change!!");
e.Cancel = true;
}
}
Straight from MSDN:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
In your case you don't need to do anything to explicitly close the form. Unless you cancel it it will close automatically, so your code would be:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
// do nothing
} else {
e.Cancel = true;
}
}
You can run any code you want when closing the form then, hide the form instead of closing it to prevent it from being disposed
yourFormName.FormClosing += (s, e) =>
{
// any code you want
yourFormName.Hide(); // this hides the form
e.Cancel = true; // this cancels the close event, you can put any boolean exprission
};

Categories