Trouble with Form.DialogResult - c#

private void mnuCustomerAdd_Click(object sender, EventArgs e)
{
CustomerForm frmCust = new CustomerForm("Add A New Customer");
int index = lstCustomers.SelectedIndex;
if (index != -1)
frmCust.CustomerData = new Customer(customerMngr.GetCustomer(index).ContactData);
MessageBox.Show("dev1");
DialogResult dr = frmCust.ShowDialog();
if (dr == DialogResult.OK)
{
MessageBox.Show("dev2");
if (frmCust.ReadInput())
{
MessageBox.Show("dev3");
customerMngr.AddCustomer(frmCust.CustomerData);
}
else
MessageBox.Show("Please supply all necessary fields with the correct information");
}
UpdateCustomerList();
}
Don't understand what I'm doing wrong here, I want to execute the conditional statements if the user hits OK in the Form that appears at frmCust.ShowDialog().
At the moment I can only get to "dev1".

Perhaps your dialog isn't setting the dialog result. Make sure your OK and Cancel buttons have their DialogResult properties set to what you expect.

Be sure correctly assign DialogResult property of the Form before it closed.
So it will be returned like a return value of ShowDilaog() call.
There is another option too, is use AcceptButton and CancelButton, in order to handle corresponding Enter and Cancel keypress.

Place a Breakpoint (F9) on the line:
if (dr == DialogResult.OK)
When the dialog closes you will have chance to examine what dr is set to.
To get the Dialog to return DialogResult.OK you can either set it in the OK button of the Dialog:
void buttonOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
Close();
}
Or you can do the option in Tigran's answer.

Related

How to handle form closing events

I am using Windows Forms in c# and have problems with how and when the the different forms (i have 2) should close and not. It is very annoying since i feel that i should be able to fix it. But here we go.
I have two forms, one MainForm that calls another form called ContactForm.
The MainForm:
private void btnAdd_Click(object sender, EventArgs e)
{
ContactForm frmContact = new ContactForm();
int index = lstCustomers.SelectedIndex;
//If a customer is selected, export data for the selected customer to ContactForm
if (index != -1)
{
frmContact.ContactData = customerMngr.GetCustomer(index).ContactData;
}
if (frmContact.ShowDialog() == DialogResult.OK) //Show the ContactForm object
{
//The user has chosen the OK button - add the new customer object
customerMngr.AddCustomer(frmContact.ContactData); //??
UpdateCustomerList();
}
if (frmContact.ShowDialog() == DialogResult.Cancel)
{
return;
}
}
And the form that is called:
OK button.
private void btnOK_Click(object sender, EventArgs e)
{
if (ValidateInput())
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
Cancel button:
private void btnCancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to cancel and discard all data?", "Cancel input", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
When the OK button in the ContactForm is used i want it to close, which works. When i press the cancel button, and no (in the box that appears), i want the form to stay open with the input still intact. Right now it doesn´t work.
Any ideas?
/Martin
Your code is alright. I think the problem lies in your Cancel Button itself. By this I mean that you probably attached (by designer or somewhere in code) DialogResul.Cancel to your button btnCancel.DialogResul property. To fix this simply set it to DialogResult.None.
If I'm right this is what is closing your second form.
See MSDN for more information.

C# how to send a message from one form to other just before close the form?

I have a program where I want it to ask a confirmation before close. It's just a simple form with the question and a yes and a no buttons. How can I send the information of which button was clicked back to the main form? All solutions I found were for communication with both forms opened, but when choosing a button in the second for it will close. Any tips or ideas?
The second type of form you described is similar to the MessageBox… You can use its direct implementation as a dialog. Untested Example :
DialogResult dr = MessageBox.Show("Are you Sure?",
"Confirm Exit?",
MessageBoxButtons.YesNo);
if (dr==DialogResult.Yes)
{
// Do work If Yes
}else //if( dr == DialogResult.No)
{
// Do work if No
}
See MSDN for MessageBox
I tend to do it this way.
Code for child form:
private bool _bDoSomething=false;
public bool showForm()
{
this.ShowDialog();
return _bDoSomething;
}
private void btnOK_Click(object sender, EventArgs e)
{
_bDoSomething=true;
this.Hide();
}
And then this sort of code for the parent form:
dlgMyForm dlgMyForm = new dlgMyForm();
if (dlgMyForm.showForm())
{
//do something
}
Declare a boolean value in main form as public
public Boolean check =false;
In the second form's FormClosing event do the following
private void Form2_FormClosing(Object sender, FormClosingEventArgs e)
{
DialogResult answer = MessageBox.Show("[Your text]",MessageBoxButtons.YesNo)
if(answer == DialogResult.Yes)
{
Form1.check=True; //if button yes is clicked
// set the form1 check variable to True and closes form2
}
else
{
Form1.check=False; //if button no is clicked
// set the form1 check variable to False and cancel form
// closing
e.Cancel=True;
}
}
Use the boolean variable check to do further processing in form1

c# : Create a connect button

I have a login form and a button which check if the user name and the password are true.
but the problem is the code I tried .. I must click on the connect button twice.
but the code should work when I click on the button just once ! Right ?
I think the problem is: the showDialog won't be disappeared if only I click in some button that it's DialogResult set in some value, so in the first click the connexionButton.DialogResult gets the DialogResult.OK value and in the second click the button executes the code.
*you can notice that the event simpleButton1_Click is the event for the connexionButton Button*
this is the event I used :
this.connexionButton.Click += new System.EventHandler(this.simpleButton1_Click);
this is the code I tried :
private void simpleButton1_Click(object sender, EventArgs e)
{
Boolean allowCnx = false;
foreach (var row in myClass.ds.Tables["Users"].AsEnumerable())
{
if (row[1].ToString().ToLower() == idBox.Text.ToLower() && row[2].ToString().ToLower() == mdpBox.Text.ToLower())
{
allowCnx = true;
}
}
if (allowCnx)
{
connexionButton.DialogResult = DialogResult.OK;
}
else
XtraMessageBox.Show("Invalide Information", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
and this is the code I used to call this login form :
using (login loginForm = new login())
{
var result = loginForm.ShowDialog();
if (result == DialogResult.OK)
this.Show();
else
this.Close();
}
// Points to a different method than the one you posted
// (simpleButton1_Click_1 instead of simpleButton1_Click)
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click_1);
// This isn't simpleButton1_Click_1
private void simpleButton1_Click(object sender, EventArgs e)
Not sure if that is your issue, but it looks like your event handler is a different method than the one you posted. Do you have another method called simpleButton1_Click_1 somewhere in your code and you've just gotten slightly confused?
EDIT: In response to your changes/additions
You seem to have some confusion over ShowDialog and DialogResult.
// When you launch the login form, I do not know what you intended to do with your
// calls to Show() and Close() but so long as you don't instend for them to do
// anything to the loginForm, that's fine.
using (login loginForm = new login())
{
if (loginForm.ShowDialog() == DialogResult.OK)
// Do stuff if logged in
else
// Do stuff if failed
}
private void simpleButton1_Click(object sender, EventArgs e)
{
Boolean allowCnx = false;
foreach (var row in myClass.ds.Tables["Users"].AsEnumerable())
if (row[1].ToString().ToLower() == idBox.Text.ToLower() && row[2].ToString().ToLower() == mdpBox.Text.ToLower())
{
allowCnx = true;
}
if (allowCnx)
{
this.DialogResult = DialogResult.OK; // Don't set the DialogResult of a button. Set it for the form.
}
else
{
this.DialogResult = DialogResult.Abort; // Because we didn't succeed
XtraMessageBox.Show("Invalide Information",
"Erreur",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
You are using simpleButton1_Click_1 instead of simpleButton1_Click.
Infact the code should be:
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
EDIT :
yes I just forgot when I copied the event.. I mean
this.connexionButton.Click += new
System.EventHandler(this.simpleButton1_Click);
I think, in this case, you should use a bool instead of a DialogResult, so try:
public bool AllowConnection = false;
private void simpleButton1_Click(object sender, EventArgs e)
{
foreach (var row in myClass.ds.Tables["Users"].AsEnumerable())
{
if (row[1].ToString().ToLower() == idBox.Text.ToLower() && row[2].ToString().ToLower() == mdpBox.Text.ToLower())
AllowConnection = true;
}
if (!AllowConnection)
XtraMessageBox.Show("Invalide Information", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
And:
using (login loginForm = new login())
{
loginForm.ShowDialog();
if (loginForm.AllowConnection)
this.Show();
else
this.Close();
}
Change your iterator for your rows from AsEnumerable to Rows.
FROM:
foreach (var row in myClass.ds.Tables["Users"].AsEnumerable())
TO:
foreach (var row in myClass.ds.Tables["Users"].Rows)
This may sound odd, but if there is any change to that table, anywhere, while you are iterating through your enumerable it will break your iteration. See DataTableExtensions.AsEnumerable This could be perhaps another process accessing this table at the same time, or using a datareader that has not completed filling the table in before the iteration starts.
Also, try to change your code to access the form's dialog result directly, instead of through the button.
FROM:
connexionButton.DialogResult = DialogResult.OK;
TO:
this.DialogResult = DialogResult.OK;
Your code should only set that if your boolean value is set to true, so you will not be closing the form if your checks are correct.
You need to set the Form.DialogResult to DialogResult.OK, not the DialogResult of the Button.
Some Code:
this.DialogResult = DialogResult.OK
Some Additional Thoughts:
It's clearly better to build a standalone method to check for
existence of the user. Don't do this in the ClickEvent. Maybe you need this method again and then you will rewrite this. This will only produce bloated code.
Prevent Users from clicking the Button before Textboxes are filled with values.

Why the new Form is close on the second time i click OK and the textBox is empty?

private void button2_Click(object sender, EventArgs e)
{
cl = new ChangeLink();
cl.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = cl.ShowDialog(this);
if (dr == DialogResult.Ok)
{
if (cl.getText() == "")
{
MessageBox.Show("The TextBox Cannot Be Empty");
cl.ShowDialog(this);
return;
}
else
{
label4.Text = cl.getText();
cl.Close();
}
}
else if (dr == DialogResult.Cancel)
{
cl.Close();
}
cl is a new Form i mgetting the text from.
Now im check that if cl.getText() is empty "" its throwing a message to the user and when the user click ok on the messagebox i want it to return and show the new Form dialog again.
When i click once on the OK button of the new Form and it show the messaeBox message and then show me again the dialogresult box of the new Form but then when i click on OK again and the textBox is still empty it doesnt show the messageBox again just close the new Form and set label4 text to be empty.
I want that each time the user click OK and the textBox is empty it will keep show the new Form textBox dialog untill the user click Cancel or put something in the textBox and then click OK.
It wiil be a lot cleaner if you do the checking in your second Form. You will need to add code to your Form2's OK Button's Click Event. Make sure you remove the default DialogResult from the OK Button Property's.
private void button2_Click(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(textBox1.Text))
DialogResult = DialogResult.OK;
}

Keeping the parent DialogButton open after the child DialogButton is closed

I'm having a problem in keeping the Parent Form to be opened till I close after using ShowDialog() .
I've been trying regarding this but couldn't get. I think there is something simple that I might have been missing. Can you please help me reg this?
The problem is,
I have Form 1, on pressing one button, Form 2 opens.
I do some validations in Form 2, and check for the validations. If the validation doesn't pass, I open a DialogBox form, with Retry and Cancel.
If I press Retry, The control should go back to the Form 2 and form 2 should not close.
If the press Cancel, both the DialogBox form and the Form 2 should close. Right now, regardless of what I press, both the forms close.
I have looked online and couldn't find any solution. Went through this solution, but both the forms are still closing for me.
Why does closing a nested child dialog also close the parent dialog?
My code:(Sample example scenario)
Form 1:
private void button1_Click(object sender, EventArgs e)
{
Form2 testForm = new Form2();
DialogResult dialogResult = new DialogResult();
dialogResult = testForm.ShowDialog(this);
if(dialogResult == DialogResult.OK)
{
//Do something
}
}
Form 2:
private void button1_Click(object sender, EventArgs e)
{
DialogResult validDataResult = MessageBox.Show("Invalid Data Entered. Please provide the correct data."
, "Data Management"
, MessageBoxButtons.RetryCancel);
if (validDataResult == DialogResult.Cancel)
{
this.Close();
}
}
in Form2.cs do your validation and then
(assuming validationOK is the true/false result of your checks)
if(validationOK == false)
{
// Ask retry or cancel to the user
if(DialogResult.Cancel == MessageBox.Show("Validation Fail", "Validation failed, press retry to do it againg", MessageBoxButtons.RetryCancel))
this.DialogResult.Cancel; // Set the dialog result on form2. This will close the form.
// if you have the validation done in a button_click event and that button has its
// property DialogResult set to something different than DialogResult.None, we need
// to block the form2 from closing itself.
// uncomment this code if the above comment is true
// else
// this.DialogResult = DialogResult.None;
}
You have to set the DialogResult of Form2 before you can call this.Close(). Otherwise, it remains the default. (The below code is only a guess of the actual double close logic since you did not specify that)
Form2.cs:
if (validDataResult == DialogResult.Cancel)
DialogResult = DialogResult.Cancel;
else
DialogResult = DialogResult.OK;
Close();
Form1.cs:
if(dialogResult == DialogResult.OK)
{
Close();
}
else
{
//Do something
}

Categories