Tom
Tom

Reputation: 15011

Returning a value from a prompt dialog

I have an application that reads through a bunch of text and looks for certain values, when these are picked up the user is prompted with a dialog box to enter a new value.

The issue I am having is that I cannot seem to call this value outside of its method.

Below is the code that calls the prompt:

return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";

When the user adds the value this is returned as follows:

System.Windows.Forms.Control.Text.get returned  "1234"  string

What I am now wanting to do is call this value in another method so that I can do string.Replace.

Any help is appreciated.

** EDIT **

Full method is as below;

public static string ShowDialog(string text, string caption)
{
    Form prompt = new Form()
    {
        Width = 500,
        Height = 150,
        FormBorderStyle = FormBorderStyle.FixedDialog,
        Text = caption,
        StartPosition = FormStartPosition.CenterScreen
    };
    Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
    TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
    Button confirmation = new Button() { Text = "Add", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
    confirmation.Click += (sender, e) => { prompt.Close(); };
    prompt.Controls.Add(textBox);
    prompt.Controls.Add(confirmation);
    prompt.Controls.Add(textLabel);
    prompt.AcceptButton = confirmation;

    return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";

Upvotes: 1

Views: 1040

Answers (1)

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

You'll have to create a property with a public getter on your prompt dialog. You can read the value from that property after ShowDialog has been called. In fact, as long as the form is not disposed, you can access that property.

using( var frm = new PromptForm())
{
   if( frm.ShowDialog() == DialogResult.OK )
   {
       var s = frm.SomeProperty;
   }
}

Upvotes: 2

Related Questions