When I press Disconnect button in form, is asking me if Yes or No. I press No, but then I can do only one action in program because after that, it crashes. Why?
private void button3_Click(object sender, EventArgs e)
{
DialogResult dialres = MessageBox.Show("Sunteti sigur ca vreti sa va deconectati?",
"Atentie!", MessageBoxButtons.YesNo);
if (dialres == DialogResult.OK)
{
try
{
_conn.Close();
_conn = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
button1.Enabled = true;
stopbut();
}
else if (dialres == DialogResult.No)
{
return;
}
}
Your first if will never be true, because you are testing for OK, not for YES. In your second if you have a return statement, so your method will finish. So not really sure what else you expected?
when you press 'No' nothing change so there should be another reason for crash, maybe that one action you do cause the crash. when you do any action your program crash or a specific one?
Edit: put the code of action that cause the crash
sorry everyone, i should comment not answer :( but i cant comment because commenting needs 50 reputations and i have only 39
and your code maybe more efficient like this:
private void button3_Click(object sender, EventArgs e)
{
DialogResult dialres =;
if ( MessageBox.Show("Sunteti sigur ca vreti sa va deconectati?",
"Atentie!", MessageBoxButtons.YesNo) == DialogResult.No) return;
//when it ain't 'No' it is definitely 'Yes'
try
{
_conn.Close();
_conn = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
button1.Enabled = true;
stopbut();
}
else if (dialres == DialogResult.No)
{
return;
}
}
Related
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.
The student is back! I am trying to self-teach C#, so please pardon my simple but many questions. I appreciate you all.
I am working on a quiz app.What I want but cant seem to achieve is that when "Testing mode" (radio button) is selected, "Number of questions" need to be grayed out.Otherwise, student can select number of questions to attempt.
Here is my code
private void rdotesting_CheckedChanged(object sender, EventArgs e)
{
if (MessageBox.Show("You have selected Testing Mode.Do you want to continue?", "Confirm Choice", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
MessageBox.Show("Click 'Start' to continue..");
btnclose.Hide();
}
else
{
MessageBox.Show("You Must select an option to continue.");
}
}
//if testing mode, dissable number of questions ,and also the 'Close' button
Like this - see comments
private void rdotesting_CheckedChanged(object sender, EventArgs e)
{
//this event fires when rdotesting is checked or when it is unchecked (change)
//set the enabled state of the nud/button to th opposite of the checked state
//ie when checked = true then enabled = false
numberQsNUD.Enabled = !rdotesting.Checked;
closeButton.Enabled = !rdotesting.Checked;
//if not in test mode, exit to stop the message showing every time
if(!rdotesting.Checked)
return;
if (MessageBox.Show("You have selected Testing Mode.Do you want to continue?", "Confirm Choice", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
rdotesting.Checked = false; //user said no; turn off test mode
simply you can try this code...
private void rdotesting_CheckedChanged(object sender, EventArgs e) {
if(rdotesting.Checked) {
numberQsNUD.Enabled = false;
closeButton.Enabled = false;
} else {
numberQsNUD.Enabled = true;
closeButton.Enabled = true;
}
}
or you can customize this via using this code...
private void EnableComponent(bool check) {
numberQsNUD.Enabled = check;
closeButton.Enabled = check;
}
private void rdotesting_CheckedChanged(object sender, EventArgs e) {
if(rdotesting.Checked) {
EnableComponent(false);
} else {
EnableComponent(true);
}
}
i have 4 errors and im working on my save button if i could get these fixed it will only save the selected items that the user wants
THIS IS NOT all the code just the code that im having problems with. this program is for and icecream application with 2 combo boxes and 3 check boxes
I PUTT COMMENT LINES WHERE I HAVE THE ERRORS ARE AT
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(
new FileStream(sfd.FileName,
FileMode.Create,
FileAccess.Write)
);
if(flavorBox) // i have an error right here (Cannot implicitly convert type 'System.Windows.Forms.ComboBox' to 'boolean)
{
sw.WriteLine(flavorBox.SelectedItem);
}
else(syrupBox) //syays i need semecolons right here for some reason
{
sw.WriteLine(syrupBox.SelectedItem);
}
if (Nuts.Checked)
{
this.Tag = "checked";
sw.WriteLine(Nuts);
}
else(Cherries.Checked) //says i need semicolons here to i dont know why
{
this.Tag = "checked";
sw.WriteLine(Cherries);
}
if(Sprinkles.Checked)
{
this.Tag = "checked";
sw.WriteLine(Sprinkles);
}
sw.Close();
}
}
THIS IS MY 4TH ERROR
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to send the data back?",
"Data Sender",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
e.Cancel() = true; //ITS ASKED ME AM I MISSING A DIRECTIVE OR ASSEMBLY REFRENCE (FOR CANCEL)
}
In an if-else only the if should have a condition, and the else should not. Use an else if statement to explicitly define a condition.
if (Nuts.Checked)
{
this.Tag = "checked";
sw.WriteLine(Nuts);
}
else if(Cherries.Checked)
{
this.Tag = "checked";
sw.WriteLine(Cherries);
}
else if(Sprinkles.Checked)
{
this.Tag = "checked";
sw.WriteLine(Sprinkles);
}
Flavorbox is a textbox, so by doing if(flavorbox) you are checking if flavorbox is equal to true or false. It's a textbox so this isn't possible. You'll probably have to just change the flavorbox. Try the following:
if(!String.IsNullOrEmpty(flavorbox.Text)) {
sw.WriteLine(flavorBox.SelectedItem);
}
1. about
if(flavorBox)
what are you checking?
about the:
else(syrupBox) and else(Cherries.Checked)
you cannot do else(something).
you can do else if(something)
because else is all the rest of the options.
so change them to:
else if(syrupBox) and else if(Cherries.Checked)
2. about the cancel:
what are you trying to do?
when you click no in the dialog, what are you trying to accomplish with the e.cancel?
For the fourth error, note that EventArgs.Cancel is a property, not a method. Remove the brackets:
e.Cancel = true;
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 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
};