-2
public static class Prompt
    {
        public static string ShowDialog(string text, string caption)
        {
            Form prompt = new Form();
            prompt.Width = 435;
            prompt.Height = 122;
            prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
            prompt.Text = caption;
            prompt.StartPosition = FormStartPosition.CenterScreen;
            Label textLabel = new Label() { Left = 10, Top=10, Width=400, Text=text };
            TextBox textBox = new TextBox() { Left = 10, Top=30, Width=400 };
            Button confirmation = new Button() { Text = "Ok", Left=300, Width=100, Top=52 };
            confirmation.Click += (sender, e) => { prompt.Close(); };
            prompt.Controls.Add(textBox);
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.AcceptButton = confirmation;
            prompt.ShowDialog();
            return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : null;
        }
    }

I created this class, so that if the user clicks the ok button it returns the value of the textbox, but if they click close it returns null. It works, the only problem is that both the red x and ok button need to be clicked twice in order for the form to actually close. How can I fix this?

SDK4
  • 59
  • 1
  • 9
  • 1
    Possible duplicate http://stackoverflow.com/questions/7163753/winforms-close-sets-dialogresult-to-cancel – RAnand Feb 02 '15 at 15:44
  • 3
    Please clarify your specific problem or add additional details to highlight exactly what you need. It’s hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question. – Andrey Korneyev Feb 02 '15 at 15:44
  • this is not a trivial issue it's pretty basic at best @SKD4 perhaps you should start utilizing the free tool known as `GOOGLE` – MethodMan Feb 02 '15 at 15:48
  • @AndyKorneyev I edited to make it more specific. – SDK4 Feb 02 '15 at 16:07
  • You're calling `ShowDailog` twice. That's why you must click the X twice. – Chris Dunaway Feb 02 '15 at 17:00

2 Answers2

0

Your prompt.ShowDialog() is the code being executed on the first instance of clicking the Red X. Since there is no code to handle it, nothing occurs. The next time you've clicked the Red X it drops out of the Prompt.ShowDialog() method.

Basically that showDialog method is in a wait-state immediately after this line: prompt.ShowDialog();

And until input is provided it's sitting just before the return statement here: return prompt.ShowDialog() == DialogResult.Cancel ? null : textBox.Text;

This doesn't solve your problem but it does clarify it well enough that you should be able to work through it.

Jeremy Little
  • 354
  • 1
  • 3
  • 11
0
confirmation.DialogResult = DialogResult.OK;

You need to set the OK button

SDK4
  • 59
  • 1
  • 9