Reputation: 81
My intention is to make a pop up window (using another form) and show it when the delete file event is triggered. On this pop up form user should enter a correct password and then click OK button, this pop up disappears and the deletion operation proceeds. What I did is setting a string variable "Result" in the pop up form(form 2). When clicking the OK button, if the password entered is correct the "Result" is set for example "true". In my main form I made like:
if(form2.Result=="true"){ // deletion operation}
However this method doesn't work. When I entered the correct password and click OK in form2, nothing happens in my main form. Anybody got any idea how could I in main form detect the button click event in form2? Something like "if(form2.button.click==true)". Thank you
Upvotes: 1
Views: 5971
Reputation: 2296
You are not supposed to detect a button click on the second form, you should restructure your flow.
There are two common ways to do this. The easiest for you to implement would be instead of calling form2.Show() which you are probably doing right now, you should call form2.ShowDialog() which will halt the execution of the method in form1 until form2 is closed
So in form1 you'd have something like
private void DeleteSomething() {
if (form2.ShowDialog() == DialogResult.Ok) {
if (form2.result == true)
doDelete();
}
}
Note that checking for the DialogResult is a common practice, and unless you assign the property on Form2 specifying which button will act as the "Ok" button, you need to manually set the dialog result inside form2 like Sayse mentioned in his reply with
this.DialogResult = DialogResult.OK;
In your case, using the dialog result is not strictly necessary, but it's a common practice to implement support for different dialog results (ok, cancel, etc)
The whole other method is to not treat form2 as a dialog, but have form1 pass a reference to itslef to form2
then in form2 you can call a method on form1 to "authorize" the delete
so form1 would have one private method "confirmDelete" which would just show form2
and another public method "doDelete" which would be called by form2 when needed.
Unrelated note on your code:
If you are going to use a variable to indicate weather the authentication was succsefull, don't use a string with the value of "true", use a boolean.
If you wanted to return 3 or more states (eg, Result could be "Ok" "User Canceled" "Incorrect password" "Inssuficcient privileges", etc) then use an Enumeration.
Upvotes: 3
Reputation: 43300
ShowDialog()
method returns a DialogResult
which you can set to indicate how the form exited
using(var form2 = MyFormName())
{
if(form2.ShowDialog() == DialogResult.OK)
//success -- You can access form2 properties also.
}
Inside your button_ok event on the form, set the DialogResult to OK
this.DialogResult = DialogResult.OK;
Upvotes: 1