How to set DialogResult AFTER button is pressed? - c#

I am creating a password window using Windows Form Designer, except the context is a little different. There are several input fields, and one of them is password protected. There is a "Change" button that spawns a new password window on top of the home window. The user enters a password attempt and presses "OK". I need a way to have the OK button check the password and then send a DialogResult.OK back to the home window, or display an "incorrect password" if the attempt is incorrect. This means I can't set the DialogResult to DialogResult.OK initially, so I'm not sure how to do this.
Currently I set the DialogResult to DialogResult.OK in the click event function, but obviously this sets it for the next click, not the current one, so the user has to press the OK button twice.
private void buttonOK_Click(object sender, EventArgs e)
{
string passwordAttempt = textBoxPassword.Text;
if( passwordAttempt.CompareTo("pass") == 0 )
{
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
One possible solution is to trigger a second event through the code (not sure how to do this). Or alternatively, is there a better way to do password windows I'm not thinking of in this situation?

Set the AcceptButton of the dialog to buttonOK (the OK button). You can do this either in code or designer.
Set the DialogResult of the dialog form, not the button.
Code:
this.AcceptButton = buttonOK;
...
private void buttonOK_Click(object sender, EventArgs e)
{
string passwordAttempt = textBoxPassword.Text;
if (passwordAttempt.CompareTo("pass") == 0)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
Close();
}
}

Related

Validating form close infinite loop

I am creating a small project using winforms + c#, I have an issue in that I am using a second form in my project as a dialogue box. When the user attempts to close this I'd like to provide them with a confirmation screen to prevent any data loss in closing the form. This dialogue box form will also feature a 'home' button, closing the dialogue box form leaving them with the main window again. The problem arises when the windows X button is pressed at the top of the screen requiring me to set up an 'on form close' event to manage. This however creates an infinite loop with my current code shown below. Is there any way to avoid this?
private void frmCreateRoute_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult Safe_to_exit_check = MessageBox.Show("Are you sure you would like to go to the home screen? \n(Any entered data will be lost.)", "", MessageBoxButtons.YesNo);
if (Safe_to_exit_check == DialogResult.Yes)
{
this.Close();
}
}
and a simple:
private void Home_button_Click(object sender, EventArgs e)
{
this.Close();
}
for the home button.
Thanks
In your FormClosing, set:
e.Cancel = true;
to prevent closing the form. Don't use this.Close() there.
You need to set e.Cancel=true if the user select any thing different than DialogResult.Yes, otherwise let the form close:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show("Are you sure you want to close the form?",
"Close", MessageBoxButtons.YesNoCancel);
if (result != System.Windows.Forms.DialogResult.Yes)
e.Cancel = true;
}

C# - Override the Standard Windows Close Button to Pop-up my Custom Form

Yes, noob question. My apologies.
When users click on the red x button on the window, I want to pop up a message asking if they really would want to quit. I found a similar question on this site: Override standard close (X) button in a Windows Form.
The thing is, I want to customize the font and the MessageBoxIcon for the MessageBox, and sadly it can't be done (or will take a lot of effort to be done). So, I've decided to make my own form.
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (txtID.Text != "" || txtPassword.Text != "")
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
new formConfirmExit().ShowDialog();
}
}
I added this code under the main form. However, when I run my code and I click on the standard close button, my pop up (the custom form I did) doesn't do what it's job. Suppose I click the "No" button, it terminates my entire program. With the "Yes" button, the pop-up shows up again, and then everything kinda stops (on Visual Studio) and ta-da! an exception.
BTW, these are the Yes and No button methods (from my Custom Form's class):
private void btnYes_Click(object sender, EventArgs e)
{
Application.Exit(); // terminate program (exception is in here)
}
private void btnNo_Click(object sender, EventArgs e)
{
this.Close(); // close this pop up window and go back to main window
}
Changing Application.Exit() to Environment.Exit(0) did the job for the Yes button, but my No button, well, terminates the program, still.
Edit: When I click on the Yes button, the pop-up/my custom form shows again (just one time). It'll stay on that state (I can click on the Yes button repeatedly yet nothing happens). The InvalidOperationException is thrown when I click the Yes button first (note the first sentence of this paragraph) then the No button.
Thank you.
Add this in your No_Click:
private void btnNo_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.No;
}
Then, change your forms closing event to the following:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (txtID.Text != "" || txtPassword.Text != "")
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown
|| e.CloseReason == CloseReason.ApplicationExitCall)
return;
// Confirm user wants to close
using(var closeForm = new formConfirmExit())
{
var result = closeForm.ShowDialog();
if (result == DialogResult.No)
e.Cancel = true;
}
}
}
First, it checks if the form isn't closing through Application.Exit(), this may be triggered from your other form, so it will not reshow the custom MessageBox.
Second, you create a using statement around your custom form. This way you can preserve the values. You then set the dialogresult to no, if the user doesn't want to cancel. If this is the case, set e.Cancel = true to stop from exiting.

How to prevent modal dialog form to close after pressing OK?

I have a (login) form that use it as modal like this (parent form code):
using (var login = new Login())
{
login.ShowDialog();
}
I do some checks on opened modal dialog and I want that it not close on pressing OK button if user name and password was wrong.
My login:
private void goSignIn_Click(object sender, EventArgs e)
{
var loggedInCustomer =LoginController.signIn(usernameBox.Text, passwordBox.Text);
if (loggedInCustomer == null)
{
MessageBox.Show("Wrong username or password! :( ", "Wrong!");
}
else
Close();
}
Check the button (goSignIn) DialogResult property. If it's set, it automatically close the form.
If the DialogResult for this property is set to anything other than None, and if the parent form was displayed through the ShowDialog method, clicking the button closes the parent form without your having to hook up any events. The form's DialogResult property is then set to the DialogResult of the button when the button is clicked.
MSDN Button.DialogResult Property
I guess you've set the DialogResult of goSignIn button to some value(probably DialogResult.OK), remove that line, everything should work fine as expected.
Don't call close then
private void goSignIn_Click(object sender, EventArgs e)
{
var loggedInCustomer =LoginController.signIn(usernameBox.Text, passwordBox.Text);
if (loggedInCustomer == null)
{
MessageBox.Show("Wrong username or password! :( ", "Wrong!");
}
else
{
Close();
}
}

Popout window issue for WPF

Now, I got a Installation Window, which have a cancel button to
1) pause the storyboarding
2) popout my Cancel Window
For Cancel Window, there will be an "OK" button for me to be prompted to Failed Window.
So now I want to know how to track when the User closes the window (X) button, so I can close the Cancel Window and thus returning to Installation Window and resume my storyboarding.
So far, I've done this
private void cancel_btn_Click(object sender, RoutedEventArgs e)
{
Storyboard SB = (Storyboard)FindResource("Install");
SB.Pause();
popout_Cancel MyApp = new popout_Cancel();
MyApp.Show();
if (MyApp.OK.IsMouseCaptured == false)
{
MyApp.Close();
SB.Resume();
}
}
You can show the window as a model dialog and use DialogResult to get the result.
If I understand you correctly, you want to know if the user pressed cancel vs if they just closed the window? I'm not sure if this is what your asking, but if you just want to show a confirmation dialog, and get the result, here's how:
In your cancel window:
private void CancelWindow_OnOkClickedobject sender, RoutedEventArgs e)
{
this.Close();
}
private void CancelWindow_OnCancelClickedobject sender, RoutedEventArgs e)
{
this.DialogResult = true;
this.Close();
}
Then, when you want to show this window:
popout_Cancel MyApp = new popout_Cancel();
bool? result = MyApp.ShowDialog();
If the user presses cancel, result will be set to true. If the user hits the X button, or presses OK, result will be set to false.
Once you have the result, you can resume your storyboard. So the code would look like this:
Storyboard SB = (Storyboard)FindResource("Install");
SB.Pause();
popout_Cancel MyApp = new popout_Cancel();
bool? result = MyApp.ShowDialog();
if (result == null || result == false)
SB.Resume();
else
//they really want to cancel, terminate the app
Edited: ShowDialog() returns a Nullable, although ShowDialog() apparently only returns true or false

Modal Dialog Box

I have created two forms in my Windows Application.
One Form acts as a Form and the other form acts as a MODAL DIALOG BOX.
The Form Dialog Box contains a button and One textBox.
When this button is clicked the MODAL DIALOGBOX should be displayed.
This dialog box also contains One Textbox and Two Buttons(Ok and Cancel).
Now when this dialog box is displayed the TextBox of the dialog box should contain the value entered in the textbox of Form1.
I have used the following coding to accomplish this task.
Form1 Coding:
public string UserName;
private void btnFn_Click(object sender, EventArgs e)
{
UserName = txtUserName.Text;
frmFnC objFnC = new frmFnC();
objFnC.ShowDialog();
objFnC.txtUserName.Text = UserName;
}
Code in MODAL DIALOGBOX OK button:
Please note that the Cancel button is enabled only when the OK button is clicked.
Coding:
private void btnOk_Click(object sender, EventArgs e)
{
btnCancel.Enabled=true;
}
private void btnCancel_Click(object sender,EventArgs e)
{
this.Close();
}
The problem I am facing is the value entered by the User in the USERNAME textbox is not displayed in the TEXTBOX in the MODAL DIALOG BOX. Instead it is displaying the textbox as empty.
What should I do to get the values entered by the user in the textbox to this modal dialog box?
Can anybody help me out in performing the desired task?
Thanks in advance!!!
The problem you've got is that you're showing the dialog before you set the username.
//this shows your dialog
objFnC.ShowDialog();
//this won't happen until the dialog is closed
objFnC.txtUserName.Text = UserName;
Because the dialog is modal it won't go to the next line until the dialog is closed. You want to swap those lines round and it'll be fine.
//do this first
objFnC.txtUserName.Text = UserName;
//then show your dialog
objFnC.ShowDialog();
I'd like to point out that exposing the textbox publically isn't a really good idea though. You don't want the consumer to have implementational knowledge of your dialog.
It would be better if you added a parameter to the form constructor and then set the textbox text from within that. Then you could do the following:
//get the username
string userName = txtUserName.Text;
//create a new form passing in the username
frmFnC objFnC = new frmFnC(userName);
//display the form
objFnC.ShowDialog();
That way, the consumer isn't relying on frmFnC having a textbox named txtUserName which means you're free to change the inner workings of how you display the username. For example, you could change it to a label and you wouldn't break the consumer's code! All the consumer needs to know is that they should pass a username into the constructor.
Change:
objFnC.ShowDialog();
objFnC.txtUserName.Text = UserName
To:
objFnC.txtUserName.Text = UserName
objFnC.ShowDialog();
Set the text field in the dialogue before calling ShowDialog:
private void btnFn_Click(object sender, EventArgs e)
{
UserName = txtUserName.Text;
frmFnC objFnC = new frmFnC();
objFnC.txtUserName.Text = UserName;
objFnC.ShowDialog();
}
You need to swap the setting of the text and the ShowDialog:
public string UserName;
private void btnFn_Click(object sender, EventArgs e)
{
UserName = txtUserName.Text;
frmFnC objFnC = new frmFnC();
objFnC.txtUserName.Text = UserName; // SET THE DATA BEFORE SHOWING THE DIALOG
objFnC.ShowDialog();
}
or force a redraw of the dialog afterwards.
In order to be able to set (and get) the contents of the text box in the modal form, add this code to that form:
public string UserName
{
get { return txtUserName.Text; }
set { txtUserName.Text = value; }
}
Then, in the other form, you can set the user name:
frmFnC objFnC = new frmFnC();
objFnC.UserName = txtUserName.Text;
objFnC.ShowDialog();
I also need to ask you about the relation between the OK and Cancel buttons in the modal dialog form; it seems a bit wierd the user would need to first click OK, in order to get the Cancel button enabled, and then click Cancel to actually close the form.
I would suggest to not have any event handlers for the click events of these buttons, but instead set the appropriate values of their DialogResult property, and then set the modal form's AcceptButton and CancelButton properties. That way you can check how the dialog was closed:
frmFnC objFnC = new frmFnC();
objFnC.UserName = txtUserName.Text;
if (objFnC.ShowDialog() == DialogResult.OK)
{
// the user clicked the OK button
}
else
{
// the user clicked the Cancel button
}

Categories

Resources