Reputation: 1181
I am trying to make a custom MessageBox. I am calling a simple form with a private constructor and a static "show" method. It will have a OK and possibly a cancel button dynamically created, depending on what the user passes in. I create the Click event handler when i create the button. What I'd like to know is how to pass the DialogResult back to the caller. Here is the code to create the button (show) and the event handler.
public static DialogResult Show(string title, string message, ButtonStyle buttonStyle) {
AFGMessageBox box = new AFGMessageBox();
box.Text = title;
box.LblMessage.Text = message;
if (buttonStyle == ButtonStyle.Ok) {
Button okButton = new Button {
Width = 93,
Height = 40,
Location = new Point(x: 248, y: 202),
Text = "OK"
};
okButton.Click += new EventHandler(OkButtonEventHandler);
}
return _result;
}
private static void OkButtonEventHandler(object sender, EventArgs e) {
_result = DialogResult.OK;
}
Upvotes: 0
Views: 2001
Reputation: 205819
You don't even need to handle click events. All you need is to set the Button.DialogResult Property of the buttons you create as stated in the documentation
Remarks
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. For example, to create a "Yes/No/Cancel" dialog box, simply add three buttons and set their DialogResult properties to Yes, No, and Cancel.
I think it's self explanatory, but just in case, here is the modified version of your sample code
public static DialogResult Show(string title, string message, ButtonStyle buttonStyle) {
AFGMessageBox box = new AFGMessageBox();
box.Text = title;
box.LblMessage.Text = message;
if (buttonStyle == ButtonStyle.Ok) {
Button okButton = new Button {
Width = 93,
Height = 40,
Location = new Point(x: 248, y: 202),
Text = "OK",
DialogResult = DialogResult.OK
};
box.Controls.Add(okButton);
}
return box.ShowDialog();
}
Upvotes: 4
Reputation: 3058
Change your method AFGMessageBox.Show
as follows:
public static DialogResult Show(string title, string message, ButtonStyle buttonStyle) {
AFGMessageBox box = new AFGMessageBox();
box.Text = title;
box.LblMessage.Text = message;
if(buttonStyle == ButtonStyle.Ok) {
Button okButton = new Button {
Width = 93,
Height = 40,
Location = new Point(x: 248, y: 202),
Text = "OK"
};
box.Controls.Add(okButton); // add the button to your dialog!
okButton.Click += (s, e) => { // add click event handler as a closure
box.DialogResult = DialogResult.OK; // set the predefined result variable
box.Close(); // close the dialog
};
}
return box.ShowDialog(); // display the dialog! (it returns box.DialogResult by default)
}
Upvotes: 0